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.
The keyword this
here refers to the current object instance, on which the method was called. Because of polymorphishm, Bar
's addFive
method is called. That method refers to the a
in scope there, which is Bar
's a
. (Bar
's a
hides Foo
's a
.) That is why 8
is printed initially, and why it gets changed to 13
. However, when System.out.println(f.a);
is called at the end of main
, the compiler only sees f
as a Foo
variable, so it prints 3
-- Foo
's a
, which was never changed from 3
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments