0
public class Main {

    public static void main(String[] args){

        Class2 class2Object = new Class2();

        //class2Object
        //num1
        class2Object.setNumber(class2Object.number1, 1) ;

        class2Object.getNumber(class2Object.number1);
    }   

}

public class Class2 {
    public int number1;

    public void setNumber(int x, int value){
        x = value;

    }
    public void getNumber(int number){
        System.out.println("Class2, x = "+number);
    }
}

I have 2 class: Class2 and Main. I assign an instance variable to 1 in Main class. Why is class2Object.number1 not assign to a value of 1? Output is 0.

3 Answers 3

3

Your setter doesn't do anything:

public void setNumber(int x, int value){
    x = value;   // This just overwrites the value of x!
}

A setter should have only one parameter. You need to assign the received value to the member field:

// The field should be private.
private int number;

public void setNumber(int value){
    this.number = value;
}
Sign up to request clarification or add additional context in comments.

3 Comments

What if i have a lot of integers like number1, number2... I need a setter for every variables?
You need array of List in that case, i guess.
Most people have a separate getter and setter for each variable. It makes it much more clear what variable is being set by the method.
2

In Java, primitive types (like int) are passed by value, not by reference.

So saying:

Class2 class2Object = new Class2();
class2Object.setNumber(class2Object.number1, 1) ;

passes class2object.number1 by value, not by reference. So the parameter x in setNumber is a whole new int and is not pointing to the same location as number1 in class2object. The method just overwrites the value of the new int x and does not modify the value pointed to by number1.

In order to set the value it should be:

void setNumber(int newNumber) { this.number1 = newNumber; }

Comments

1

Since you should assign like this:

private int number1;

public void setNumber(int value){
    this.number1 = value;
}

2 Comments

you forgot to remove the unnecessary parameter.
ohh sorry, yes @twain249. you are right. I am updating my codes.

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.