Because the code is assigning the b
parameter to the b
parameter itself, and the b
attribute of the class is not being changed. When there is ambiguity, it overcomes the local symbol. If the parameter had another name, it would work. But since it is not legal to change a name just to get around this, after all this could affect the readability, it should be explicit that you want to change the class variable, indicating with this.b
. So:
class B {
private int b;
public int getB() { return b; }
public void setB(int b) { this.b = b; }
}
class A {
public static void main (String[] args) {
B b = new B();
b.setB(5);
System.out.println(b.getB());
}
}
See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .