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?..
int a += 5;won't compile. I suspect you meanta += 5;to match the code in the superclass method, which needs a semicolon.