Java Reference
In-Depth Information
When statement #3 is ready to execute, at that time the expression with the typecast still refers to an object
of
LateBindingSub
type, and therefore, the
print()
method of the
LateBindingSub
class will be called. This is
confirmed by the third line in the output.
Let's consider two lines of code to discuss statement #4:
lbSuper = lbSub; // Upcasting
lbSuper.print(); // #4
The first source line assigns
lbSub
to
lbSuper
. The effect of this line is that
lbSuper
variable starts referring to an
object of
LateBindingSub
object. When statement #4 is ready to execute, the runtime needs to find the code for the
print()
method. The runtime finds that the runtime type of the
lbSuper
variable is the
LateBindingSub
class. It looks
for the
print()
method in the
LateBindingSub
class and finds it right there. Therefore, statement #4 executes the
print()
method in the
LateBindingSub
class. This is confirmed by the fourth line in the output.
■
Late binding incurs a small performance overhead compared to early binding because the method calls are
resolved at runtime. however, many techniques (e.g. virtual method table) can be used to implement late binding, so the
performance hit is minimal or negligible. the benefit of late binding overshadows the little performance hit. It lets you
implement inclusion polymorphism. When you write code like
a2.print()
, the
a2
variable exhibits polymorphic
behavior with respect to the
print()
method. the same code,
a2.print()
, may call the
print()
method of the
class of the
a2
variable or any of its descendant classes depending on what type of object
a2
is referring to at runtime.
Inheritance and late binding lets you write polymorphic code, which is written in terms of superclass type and works for
all subclass types as well.
Tip
Method Overriding
Redefining an instance method in a class, which is inherited from the superclass, is called method overriding.
Let's consider the following declarations of class
A
and class
B
:
public class A {
public void print() {
System.out.println("A");
}
}
public class B extends A {
public void print() {
System.out.println("B");
}
}
Class
B
is a subclass of class
A
. Class
B
inherits the
print()
method from its superclass and redefines it. It is said
that the
print()
method in class
B
overrides the
print()
method of class
A
. It is like class
B
telling class
A
, “Thanks for
being my superclass and letting me inherit your
print()
method. However, I need to work differently. I am going to