Because the code is assigning the parameter b
for the parameter itself b
and the attribute b
class is not being changed. When there is ambiguity, the local symbol wins. If the parameter had another name, it would work. But since it’s not legal to change a name just to get around it, after all this could affect readability, you should make it explicit that you want to move the class variable, indicating with this.b
. Thus:
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());
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
I thought that the local symbol considered would be that of the reference, but then in the case there is a more specific: the parameter itself!
– Murillo Goulart