I am having trouble getting value from getter. I am trying to access the getter method from another class but it returns null.

In my Registration Class I have a constructor and getters.
In my Client Class I have set the values using Scanner.
I would like to create Report Class and access getters in order to print it out:

public RegistrationDetails(String name){     
      this.name = name;  
   }   
    public String getName() {
        return name;
    }

In my Client Class I used Scanner to set the name:

System.out.println("Enter Name: ");
 name = in.nextLine();


 RegistrationDetails registrationDetails = new RegistrationDetails(name);

In my Report Class when i do somthing like this:
RegistrationDetails registrationDetails = new RegistrationDetails();
registrationDetails.getName(); -- it returns NULL

Any suggestions how to fix it.

In my main class I have first called a method to set details and then to get it..

RegistrationDetails registrationDetails = new RegistrationDetails(name);

creates a new instance, and initialises the name field, but

RegistrationDetails registrationDetails = new RegistrationDetails();

creates a new instance and leaves the name field uninitialised (null)

The fix is to call getName() using the same instance that you created with a name

Thank you for quick response.

I still don't no how to pass "name" to instance RegistrationDetails registrationDetails = new RegistrationDetails() because it is in other class. And when i pass "name" it is an error

RegistrationDetails registrationDetails = new RegistrationDetails();
that version is almost certainly a mistake. The name is presumably mandatory. What use is a registration without a name?

So in your Client class you get a name and create a registration using that name. OK

Now in your report class you need to access that same registration, so you can call its getName() method. Exactly how you do that depends on how it's all set up - and I can't tell that from what you have posted. One possibility is that you create a new Report object for each report, and you pass the registration obect as a parameter to the report's constructor.

Edited 1 Year Ago by JamesCherrill

Thank you for help, it works perfectly fine now. I created a new Report object.
Thumbs up

This article has been dead for over six months. Start a new discussion instead.