Java Reference
In-Depth Information
6 public String toString() {
7
return "C";
8 }
9 }
1 public class D extends C {
2 public void method2() {
3 System.out.println("D 2");
4 }
5 }
Consider the following client code that uses these classes. It takes advantage of the
fact that every other class extends class A (either directly or indirectly), so the array
can be of type A[] . When you call methods on the elements of the array, polymor-
phic behavior will result:
1 // Client program to use the A, B, C, and D classes.
2 public class ABCDMain {
3 public static void main(String[] args) {
4 A[] elements = { new A(), new B(), new C(), new D()};
5
6 for ( int i = 0; i < elements.length; i++) {
7 System.out.println(elements[i]);
8 elements[i].method1();
9 elements[i].method2();
10 System.out.println();
11 }
12 }
13 }
It's difficult to interpret such code and correctly determine its output. In the next
section we'll present techniques for doing so.
Interpreting Inheritance Code
To determine the output of a polymorphic program like the one in the previous sec-
tion, you must determine what happens when each element is printed (i.e., when its
toString method is called) and when its method1 and method2 methods are called.
You can draw a diagram of the classes and their methods to see the hierarchy order-
ing and see which methods exist in each class. Draw each class as a box listing its
methods, and connect subclasses to their superclasses with arrows, as shown in
Figure 9.2. (This is a simplified version of a common design document called a UML
class diagram.)
A good second step is to write a table that lists each class and its methods' output.
Write the output not just for the methods defined in each class, but also for the ones
that the class inherits. Since the A class is at the top of the hierarchy, we'll start there.
 
Search WWH ::




Custom Search