i need someone help with this little code snippet; why is the output: b 3 and not b 13 as expected?
public class Foo{
int a = 3;
public void addFive() { a+=5; System.out.println("f");}
}
class Bar extends Foo{
int a = 8;
public void addFive() { this.a+=5; System.out.println("b");}
public static void main(String[] args) {
Foo f = new Bar();
f.addFive();
System.out.println(f.a);// why b 3 and not b 13 ??
}
}
Foo
and Bar
have two different a
fields; Java does not have any notion of field overriding.
Calling f.addFive()
calls the derived version of the method (since Java does do method overriding), which modifies Bar.a
.
However, accessing f.a
returns Foo.a
(since f
is declared as Foo
), which was never changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With