Why does the code print 0 instead of 5?

Asked

Viewed 122 times

4

Why does this code print 0 instead of 5?

class B {
    private int b;
    public int getB() { return b; }
    public void setB(int b) { b=b; }
}

class A {
    public static void main (String[] args) {
        B b = new B();
        b.setB(5);
        System.out.println(b.getB());
    }
}

Run it via Ideone.

3 answers

10


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!

4

You must use this.b to reference the attribute of your class. Thus, your class B code should be:

class B {
  private int b;
    public int getB() { return this.b; }
    public void setB(int b) { this.b=b; }
}

2

The code b=b; has no effect on the method public void setB(int b) class B.
When a parameter exists with the same field name (field) it is necessary to use the this to access the field and the reason you are printing 0 is because this is the initial value assigned to variables and fields of the type int.

  • When you have enough reputation, you can post comments on both the question and the answers of other users, but until then, stick to giving only answers that add something to the discussion. At the moment, your reply adds nothing in relation to the previous answers.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.