Reputation: 740
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.
Upvotes: 1
Views: 2840
Reputation: 178333
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
.
Upvotes: 3
Reputation: 302
When declaring a variable in a subclass with the same name as in the superclass, you are hiding the variable, unlike methods which are overwritten. This difference is since f points to an object of type Bar, the addFive() method in Bar is used. However, when calling f.a, its reference type is Foo and it looks for the variable there first. Hiding variables in subclasses should generally be avoided for this reason.
Upvotes: 2