psychorama
psychorama

Reputation: 323

How to assign class variable value via calling a method?

I am trying to assign value to a class variable via a method. However, after the execution comes out of the scope of the method, the variable is still initialized to the default value. How do we accomplish this in Java?

I want to initialize x to 5 by calling the method hello(). I don't want to initialize by using a 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);
    }
}

Upvotes: 2

Views: 1147

Answers (3)

aioobe
aioobe

Reputation: 420951

When you do

hello(5,x);

and then

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

it seems like you might be trying to pass the field itself as parameter to the hello method, and when doing x2 = i you meant x2 to refer to the field. This is not possible, since Java only supports pass-by-value. I.e. whenever you give a variable as argument to a method, the value it contains will be passed, not the variable itself.

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

Upvotes: 9

aakansha
aakansha

Reputation: 695

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 the value of x and getx to return the value x.

Essentially these are called getter and setter and we use them to access private members from outside the class.

Upvotes: 0

Armand
Armand

Reputation: 24333

The class property x is only visible by using this.x in hello() because you have declared another variable called x in the method's arguments.

Either remove that 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 the class property:

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

Upvotes: 1

Related Questions