Search code examples
javaconstructornullgetter-setter

Java object constructor returning "null"


New to Java! I have created a class that has constructors for various fields. However, when I try and print the fields, I recieve "null" as the output. Please help me understand why. Here is the class:`

 public class User {
   //All relevant information to identify each user.
      private String FirstName;
      private String LastName;
      private String Email;
      private long PhoneNum;
      private long CardNum;

   //Build Constructors for User info.

public User(String Fname, String Lname, String Mail, long num, long card)
{
   Fname=FirstName;
    Lname=LastName;
    Mail=Email;
    num=PhoneNum;
    card=CardNum;
}

  //Method to set FirstName.  
 public void setFirstName (String Fname) 
{
    FirstName=Fname;
}
//Method to get FirstName.
public String getFirstName()
{
    return FirstName;
}
 //Method to set LastName. 
public void setLastName (String Lname)
{
    LastName=Lname;
}


 //Method to get Lastname. 
    public String getLastname()
    {
        return LastName;
    }
    //Method to set email.
    public void setEmail (String Mail)
    {
        Email=Mail;
    }
     //Method to get email.
    public String getEmail()
    {
        return Email;
    }
    //Method to set phonenumber.
    public void setPhoneNum(long num)
    {
        PhoneNum=num;
    }
   //Method to get phonenumber.
    public long getPhoneNum()
    {
        return PhoneNum;
    }
   //Method to set credit card number.
        public void setCardNum(long card)
    `enter code here`{
        CardNum=card;
    }
     // Method to get credit card number.
         public long getCardNum()
    {
        return CardNum;
    }

Now when I run this code, I receive "null":

public class UserDemo {
public static void main(String[] args)
{
    String first="Matt";
    String last="Burns";
    String email="mburns267@yahoo.com";
   long phone=333;
   long card=222;
    User Matt=new User(first,last,email,phone,card);
    System.out.print(Matt.getLastname());
}

What am I doing wrong? Thank you in advance!

`


Solution

  • Is the other way around, instead of:

    public User(String Fname, String Lname, String Mail, long num, long card){
        Fname=FirstName;
        Lname=LastName;
        Mail=Email;
        num=PhoneNum;
        card=CardNum;
    }
    

    it should be:

    public User(String Fname, String Lname, String Mail, long num, long card){
        FirstName = Fname;
        LastName = Lname;
        Email = Mail;
        PhoneNum = num;
        CardNum = card;
    }
    

    To avoid this kind of thing you can use the this keyword. Here is an example:

    String firstName;
    public Constructor(String firstName){
        this.firstName = firstName;
    }