2

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;
    }    

}

3 Answers 3

2

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";
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.