Java Reference
In-Depth Information
11.8 Dynamic Binding
A method can be implemented in several classes along the inheritance chain. The JVM
decides which method is invoked at runtime.
Key
Point
A method can be defined in a superclass and overridden in its subclass. For example, the
toString() method is defined in the Object class and overridden in GeometricObject .
Consider the following code:
Object o = new GeometricObject();
System.out.println(o.toString());
Which toString() method is invoked by o ? To answer this question, we first introduce
two terms: declared type and actual type. A variable must be declared a type. The type that
declares a variable is called the variable's declared type . Here o 's declared type is Object . A
variable of a reference type can hold a null value or a reference to an instance of the declared
type. The instance may be created using the constructor of the declared type or its subtype.
The actual type of the variable is the actual class for the object referenced by the variable.
Here o 's actual type is GeometricObject , because o references an object created using new
GeometricObject() . Which toString() method is invoked by o is determined by o 's
actual type. This is known as dynamic binding .
Dynamic binding works as follows: Suppose an object o is an instance of classes C 1 , C 2 , . . . ,
C n-1 , and C n , where C 1 is a subclass of C 2 , C 2 is a subclass of C 3 , . . . , and C n-1 is a subclass of C n ,
as shown in Figure 11.2. That is, C n is the most general class, and C 1 is the most specific class. In
Java, C n is the Object class. If o invokes a method p , the JVM searches for the implementation
of the method p in C 1 , C 2 , . . . , C n-1 , and C n , in this order, until it is found. Once an implementa-
tion is found, the search stops and the first-found implementation is invoked.
declared type
actual type
dynamic binding
C n
C n-1
C 2
C 1
.....
If o is an instance of C 1 , o is also an
instance of C 2 , C 3 ,…, C n-1 , and C n
java.lang.Object
F IGURE 11.2
The method to be invoked is dynamically bound at runtime.
VideoNote
Listing 11.6 gives an example to demonstrate dynamic binding.
Polymorphism and dynamic
binding demo
L ISTING 11.6
DynamicBindingDemo.java
1 public class DynamicBindingDemo {
2 public static void main(String[] args) {
3 m( new GraduateStudent());
4 m( new Student());
5 m( new Person());
6 m( new Object());
7 }
8
9 public static void m(Object x) {
10 System.out.println(x.toString());
11 }
12 }
13
14 class GraduateStudent extends Student {
15 }
16
17 class Student extends Person {
18 @Override
19
polymorphic call
dynamic binding
override toString()
public String toString() {
 
 
 
Search WWH ::




Custom Search