Assigning a method from an instantiated object to a variable

Just to give an example, the beginning of the code I’m working on is similar to what’s below. I have created an object of the N class.

class Main {
  public static void main(String[] args) {
    N n = new N();
    String one = n.getPhraseX(); 
    String two;
    String three;

Lets say we have a method in the created class that looks like this:

public String getPhraseX()
return PhraseX;

When I assign this method to a variable from the Main class, String one as shown:

String one = n.getPhraseX();

I can’t get a correct value from it without always declaring:

one = n.getPhraseX();

after changing PhraseX’s value through a setter.

If I were to change the value of PhraseX through a setter, I cannot afterwards just call upon the method like this:

n.getPhraseX();

and get an updated value. It would give me an outdated value. I have to use one = n.getPhraseX();

I tested this through:

System.out.println("This is what PhraseX says: " + one);

in the line directly after the get method.

The value of String one was not what was most recently set by the setter method, even though it was intialized to always be equal to whatever is returned by the get method.

I would like to know the specifics as to why this is the case, why the value of the String one isn’t updating upon calling of the method alone.

I tried exactly as shown above, as well as moving the positioning of the intialized String in the code, as well as trying to tweak the get and set methods.

>Solution :

The value of String one was not what was most recently set by the setter method, even though it was intialized to always be equal to whatever is returned by the get method.

You’re misundertanding the "equal" operator. String one = n.getPhraseX(); does not mean "assign one to always reference the value returned by getPhraseX()". It means "copy the current value of n.getPhraseX() over to one".

So regardless of what you do with the setter for "phrase x", "one" will continue to hold the value it was assigned.

Try searching for tutorials and examples for "Java assignment" and "Java copy by value".

Leave a Reply