Java Reference
In-Depth Information
This is, at compile time, the call
methodA
( ) on
var1
will be checked against a reference type of
var1
,
ClassA
, by the compiler, and the compiler will allow it because the
methodA
( ) exists in
ClassA
.
But what will happen if we run the test; that is, which
methodA
( ) will be called,
methodA
( ) in
ClassA
or
methodA
( ) in
ClassB
? When the test is run, it gives the following output:
methodA() in ClassB
The compiler checked
methodA
( ) in
ClassA
but executed
methodA
( ) in
ClassB
. This is because at
runtime, the JVM verifies, instead of compiles,
methodA
( ) against the actual object type. The actual
object type in the code (
ClassA var1 = new ClassB();
) is
ClassB
, while
ClassA
is a reference type.
So, the JVM checks whether the call
methodA
( ) is in
ClassB
( ) and calls it. This phenomenon is called
polymorphism
. What will happen if
methodA
( ) is not in
ClassB
? To understand this, we implement the
code for Figure
A-4
.
Figure A-4.
Hierarchy of ClassB