Dog
Dog

Reputation: 605

How to change an instance variable that contains a changed instance variable

How come setWav doesn't change the wav in wav + " " + "Grapes"? Do I have to create a set method for add if I want it to output Oranges? Grapes?

EDIT: Thanks everyone for the help, much appreciated.

package javaapplication1;

public class JavaApplication1 {

    public static void main(String[] args) 
    {
        NewClass object1 = new NewClass();
        System.out.println(object1.getAdd());
        object1.setWav("Oranges?");
        System.out.println(object1.getAdd());    


    }
}


OUTPUT:

Burgers Grapes

Burgers Grapes


package javaapplication1;

public class NewClass 
{
    private String wav;
    private String add;

    public NewClass()
    {
        wav = "Burgers";
        add = wav + " " + "Grapes";       

    }

    public void setWav(String wav)
    {
        this.wav = wav;        
    }
    public String getWav()
    {
        return wav;
    }

    public String getAdd()
    {
        return add;
    }    

}

Upvotes: 2

Views: 84

Answers (3)

jonathan
jonathan

Reputation: 2576

In your example the constructor is responsible for updating "add". But the problem is that its only invoked once, which is when the class is instantiated.

It happens on this line: NewClass object1 = new NewClass();

You could change setWav into this:

public void setWav(String wav)
{
    this.wav = wav;
    this.add = wav + " " + "Grapes";
}

This way it would update add every time setWav is called.

Upvotes: 2

arshajii
arshajii

Reputation: 129487

Your getAdd method returns add. You set the value of add in the NewClass constructor but nowhere else, hence it remains unchanged even when you change wav (these two variables are not related in any way, changing one will not effect the other). You can try this:

public void setWav(String wav) {
    this.wav = wav;  
    add = wav + " " + "Grapes";  // i.e. add = wav + " Grapes";
}

Upvotes: 2

zeller
zeller

Reputation: 4974

You don't refresh add when you call setWav. Copy this line from the ctor to the setter:

add = wav + " " + "Grapes";  

And it will work.

Upvotes: 2

Related Questions