-3

So, I'm making a simple program that is using 2 classes.

The first class contains this:

public class A{
    private int x;

    public A(){
        x = changexvalue(x);
        System.out.println(x); //Check value
    }

    private int changexvalue(int x){
        x = x + 2;
        return x;
    }

    public int getxvalue(){
        return x;
    }
}

The second class contains this:

public class B{

    public static void main(String [] args){
        A a = new A();
        System.out.println(a.getxvalue());
    }
}

So, the problem is this. The first output(in class A) prints 2 but the class B output shows 0(I want the class B output show 2). How is this possible and how can I fix this?

Thanks

2 Answers2

0

Use this.x to refer to the class' member variable x. x on its own refers to the local variable.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Which local variable are you talking about. There no local variable x in A constructor. – Ostap Maliuvanchuk May 27 '14 at 14:01
  • To elaborate: in `changexvalue`, the `x` that is being changed/returned (and thus printed when `a` is created) is the local `x` (the parameter), NOT the instance variable `x`. An alternate fix would be to use a different name for the local variable. – Scott Hunter May 27 '14 at 14:01
  • this.x on the getxvalue() method or the changexvalue method? – user3680043 May 27 '14 at 14:01
  • @user3680043: Use a different name than just `x`. `y` would suffice. – Engineer2021 May 27 '14 at 14:08
  • @user3680043: `this.x` would mean the same thing (the member variable) in both, but its only in `changexvalue` that `x` does not mean the same thing as `this.x`. – Scott Hunter May 27 '14 at 14:10
  • 1
    It doesn't matter. The method returns the value of the local `x`, _which is then assigned to the instance variable `x` by the constructor._ – GriffeyDog May 27 '14 at 14:37
0

x got shadowed here. You use two variablees with the same name so only the inner variable (the input of the method at this point) is accessable and x the attribute of your class can not be accessed.

private int changexvalue(int x){
    x = x + 2;
    return x;
}

replace it with

private int changexvalue(int y){
    x = y + 2;
    return x;
}

or use this to make clear where you use the x Attribute of the class and where you use the x input variable of your method:

private int changexvalue(int x){
    this.x = x + 2;
    return this.x;
}
Simulant
  • 19,190
  • 8
  • 63
  • 98