On running this code
class c1 { int ci = 1; }
class c2 extends c1 { int ci = 2; }
class inheritanceTest {
public static void main(String args[]) {
c1 c1reftoc2 = new c2();
System.out.println(c1reftoc2.ci);
}
}
Output is 1. So i guess that a subclass object with superclass reference variable, uses superclass variable in case of variables of same name in both classes.
But then, running this program from a SCJP question,
class Foo {
public int a = 3;
public void addFive() {
a += 5;
System.out.print("f ");
}
}
class Bar extends Foo {
public int a = 8;
public void addFive() {
System.out.println(this.a);
this.a += 5;
System.out.print("b " );
System.out.println(this.a);
}
}
class SCJPQC3 {
public static void main(String[] args) {
Foo f = new Bar();
f.addFive();
System.out.println(f.a);
}
}
output is
8
b 13
3
The addFive() method called in main() would be that of class Bar because of overriding.
this.a in addFive() prints 8. Whereas f.a in main() gives 3. Instances being referred by this. and f. are same, yet they give different results. Using this.a gives 8 as output which contradicts my previous understanding.
So my question is, does this. refer to a class or an instance? I know that this. would refer to the object through which a method is called, but this particular program confused me.