Java Reference
In-Depth Information
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.
Listing 11.6 gives an example to demonstrate dynamic binding.
L ISTING 11.6 DynamicBindingDemo.java
1 public class DynamicBindingDemo {
2
VideoNote
Polymorphism and dynamic
binding demo
public static void main(String[] args) {
m( new GraduateStudent());
3
4 m( new Student());
5 m( new Person());
6 m( new Object());
7 }
8
9 public static void {
10 System.out.println(x.toString());
11 }
12 }
13
14 class
polymorphic call
m(Object x)
dynamic binding
GraduateStudent extends Student
{
15 }
16
17 class
Student extends Person
{
18 @Override
19
override toString()
toString()
public String
{
20
return "Student" ;
21 }
22 }
23
24 class
Person extends Object
{
25 @Override
26
override toString()
public String
toString()
{
27
return "Person" ;
28 }
29 }
Student
Student
Person
java.lang.Object@130c19b
Method m (line 9) takes a parameter of the Object type. You can invoke m with any object
(e.g., new GraduateStudent() , new Student() , new Person() , and new Object() )
in lines 3-6).
When the method m(Object x) is executed, the argument x 's toString method is
invoked. x may be an instance of GraduateStudent , Student , Person , or Object . The
classes GraduateStudent , Student , Person , and Object have their own implementa-
tions of the toString method. Which implementation is used will be determined by x 's
actual type at runtime. Invoking m(new GraduateStudent()) (line 3) causes the
toString method defined in the Student class to be invoked.
Invoking m(new Student()) (line 4) causes the toString method defined in the
Student class to be invoked; invoking m(new Person()) (line 5) causes the toString
Search WWH ::




Custom Search