How do I assign a value to a class variable by calling a method?

I am trying to assign a value to a class variable using a method. However, after execution leaves the scope of the method, the variable is still initialized to its default value. How do I do this in Java?

I want to initialize x to 5 by calling the hello () method. I don't want to initialize using the constructor, or using this. Is it possible?

public class Test {
    int x;
    public void hello(){
        hello(5,x);
    }
    private void hello(int i, int x2) {
        x2 = i;
    }
    public static void main(String args[]){
        Test test = new Test();
        test.hello();
        System.out.println(test.x);
    }
}

      

+3


source to share


3 answers


When you do

hello(5,x);

      

and then



private void hello(int i, int x2) {
    x2 = i;
}

      

it looks like you are trying to pass this field as a parameter to a method hello

, and when executed, x2 = i

you meant x2

to refer to that field. This is not possible since Java only supports bandwidth. That is, whenever you give a variable as an argument to a method, the value it contains will be passed, not the variable itself.

(Thanks to @Tom for pointing this interpretation of the question in the comments.)

+10


source


The class property x

is only visible with this.x

in hello()

, because you specified a different variable in the method argument x

.

Or remove this argument:

private void hello(int i) {
    x = 5;
}

      

Rename the argument:



private void hello(int i, int y) {
    x = 5;
}

      

Or use this.x

to set properties of the class:

private void hello(int i, int x) {
    this.x = 5;
}

      

+2


source


You can create two methods.

public void setX(int a)//sets the value of x
{
    x=a;
}
public int getX()//return the value of x
{
return x;
}

      

call setX

to set x value and getx

to return x value.

Basically they are called getter and setter, and we use them to access private members outside of the class.

0


source







All Articles