I'm checking some Java exercises but I'm confused with this one:
We have a Foo class with this structure:
public class Foo {
public int a = 3;
public void addFive() {
a += 5;
}
}
A Bar class who inherits from Foo:
public class Bar extends Foo {
public int a = 8;
public void addFive() {
a += 5;
}
}
And a Test class :
public class Test {
public static void main(String[] args) {
Foo f = new Bar();
f.addFive();
System.out.println(f.a);
}
}
I would think the output is 13, but it's 3, my question is Why?..
Adding to Peter's answer : keep in mind that member variables are not polymorphic, so they are not overriden.
I.e. f.a still gives you reference to super class's a (since f's declared type is Foo) whereas f.addFive() calls method on Bar, (since f's runtime type is Bar);
So, for example
Bar b = new Bar();
Foo f = b;
f.addFive();
System.out.println(f.a); // prints 3
System.out.println(b.a); // prints 13 as you have expected
Hope it is clear.
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