Java Reference
In-Depth Information
// Will access LateBindingSuper.print()
lbSuper.print(); // #1
// Will access LateBindingSub.print()
lbSub.print(); // #2
// Will access LateBindingSub.print()
((LateBindingSuper)lbSub).print(); // #3
// Assign the lbSub to lbSuper
lbSuper = lbSub; // Upcasting
// Will access LateBindingSub.print() because lbSuper
// is referring to a LateBindingSub object
lbSuper.print(); // #4
}
}
Inside LateBindingSuper.print()
Inside LateBindingSub.print()
Inside LateBindingSub.print()
Inside LateBindingSub.print()
The
main()
method creates an object of each type
LateBindingSuper
and
LateBindingSub
.
LateBindingSuper lbSuper = new LateBindingSuper();
LateBindingSub lbSub = new LateBindingSub();
The calls to the
print()
method are labeled #1, #2, #3 and #4, so we may refer to them in our discussion.
Both variables,
lbSuper
and
lbSub
, are used to access the
print()
instance method. The runtime decides
which version of the
print()
method is called. When you use
lbSuper.print()
, which
print()
method is called
depends on the object to which
lbSuper
variable is referring to at that point in time. Recall that a reference variable
of a class type may also refer to an object of any of its descendant. The
lbSuper
variable may refer to an object of
LateBindingSuper
or
LateBindingSub
.
When the statement #1,
lbSuper.print()
, is ready to execute, the runtime will need to find the code for the
print()
method. The runtime looks for the runtime type of the
lbSuper
variable and it finds that the
lbSuper
variable
is referring to an object of
LateBindingSuper
type. It looks for a
print()
method in the
LateBindingSuper
class and
finds it. Therefore, the runtime binds the
print()
method call in the statement labeled #1 to the
print()
method of
the
LateBindingSuper
class. This is confirmed by the first line in the output.
The logic for binding the
print()
method in statement #2 is the same as for the statement labeled #1, but the
class this time is
LateBindingSub
.
Statement #3 is tricky. When you use a typecast such as
(LateBindingSuper)lbSub
, the object to which
lbSub
refers to at runtime does not change. Using a typecast, all you say is that you want to use the object to which
lbSub
variable refers as an object of
LateBindingSuper
type. However, the object itself never changes. You can verify this by
using the following code, which gets the class name of an object:
// Both s1 and s2 have "com.jdojo.inheritance.LateBindingSub" class name
LateBindingSub lbSub = new LateBindingSub();
String s1 = lbSub.getClass().getName();
String s2 = ((LateBindingSuper)lbSub).getClass().getName();