Java Reference
In-Depth Information
The compiler performs only one check for the
emp.setName()
method call in the above code. It makes sure that
the declared type of the
emp
variable, which is
Employee
, has a method called
setName(String s)
. The compiler
detects that the
setName(String s)
method in the
Employee
class is an instance method, which is not
final
. For an
instance method call, the compiler does not perform binding. It will leave this work for runtime. The method call,
emp.setName("John Jacobs")
, is the case of late binding. At runtime, the JVM decides which
setName(String s)
method should be called. The JVM gets the runtime type of the
emp
variable. The runtime type of the
emp
variable is
Manager
when the
emp.setName("John Jacobs")
statement is looked at in the above code snippet. The JVM traverses
up the class hierarchy starting from the runtime type (that is,
Manager
) of the
emp
variable looking for the definition of
a
setName(String s)
method. First, it looks at the
Manager
class and it finds that the
Manager
class does not declare
a
setName(String s)
method. The JVM now moves one level up the class hierarchy, which is the
Employee
class.
It finds that the
Employee
class declares a
setName(String s)
method. Once the JVM finds a matching method
definition, it binds the call to that method and stops the search. Recall that the
Object
class is always at the top of all
class hierarchies in Java. The JVM continues its search for a method definition up to the
Object
class. If it does not find
a matching method in the
Object
class, it throws a runtime exception.
Let's look at an example that will demonstrate the late binding process. Listing 16-9 and Listing 16-10 have
code for
LateBindingSuper
and
LateBindingSub
classes, respectively. The
LateBindingSub
class inherits from the
LateBindingSuper
class. It defines the same instance method
print()
as defined in the
LateBindingSuper
class.
The
print()
method in both classes prints different messages so that you can see which method is being called.
Listing 16-9.
A LateBindingSuper Class, Which Has an Instance Method Named print()
// LateBindingSuper.java
package com.jdojo.inheritance;
public class LateBindingSuper {
public void print() {
System.out.println("Inside LateBindingSuper.print()");
}
}
Listing 16-10.
A LateBindingSub Class, Which Has an Instance Method Named print()
// LateBindingSub.java
package com.jdojo.inheritance;
public class LateBindingSub extends LateBindingSuper{
public void print() {
System.out.println("Inside LateBindingSub.print()");
}
}
Listing 16-11 demonstrates the result of late binding.
Listing 16-11.
A Test Class to Demonstrate Early Binding for Fields and Methods
// LateBindingTest.java
package com.jdojo.inheritance;
public class LateBindingTest {
public static void main(String[] args) {
LateBindingSuper lbSuper = new LateBindingSuper();
LateBindingSub lbSub = new LateBindingSub();