I ran into this example about inheritances on the web, and I am not easy regarding its results. I’m missing something critical.
public class A {
int i = 5;
public A() {
foo();
}
private void foo() {
System.out.println(i);
}}
public class B extends A {
int i = 6;}
public class C extends B {
int i = 7;
public void foo() {
System.out.println("C's foo");
System.out.println(super.i);
}}
I’m trying to figure out what’s happening by the following command: C c = new C();
System.out.println(C.i);
I know that when we create a new instance of C we approach A’s and B’s constructures, So We reach to A() – (question 1) Does i (of A) being initialize on the way?
Now we need to call to foo()– (question 2)- Does C’s foo() consider as an override of A’s foo()? and what if B had a foo() of itself? then it was consider as a override and C’s foo() was operated?
As far as I know, there is no override when it relates to local variables. How come that System.out.println(c.i) is 7 and not 5? shouldn’t it b the i of the highest-father?
EDIT: My question is not about which foo and i will be used when I use c, is about what happens during these two specific commands, cause obviously A’s foo was used and not C’s.
Thank you very much.
The three
ivariables here are completely independent. Which one is used by any statement is determined at compile-time – there’s no polymorphism involved. SoA.foo()will always print out the value of the variable declared inA.Note that these aren’t local variables by the way – they’re instance variables.
When you print out
c.ithat uses the variable declared inCbecause the compile-time type ofcisC. You can see this if you write:Note that in a well-written program this sort of thing almost never causes a problem, as variables should be private.