Java Reference
In-Depth Information
Table 9.10
Method Output for Classes E , F , G , and H
E
F
G
H
toString
F
F
G
F
method1
G 1
G 1
G 1
H 1
method2
E 2 method1()
F 2 G 2
G 2
E 2 method1()
Class H doesn't override method2 , so you may think that you can copy over its
output from superclass E . But remember that the inherited method2 prints " E 2 "
and then calls method1 . In this case, we are thinking from the perspective of an H
object. So that inner call to method1 now prints " H 1 " instead of the old output.
This means that calling method2 on an H object actually prints " E 2 H 1 " . Table 9.10
shows the final output for all methods.
9.4 Inheritance and Design
Inheritance affects the thought processes you should use when designing object-
oriented solutions to programming problems. You should be aware of similarities
between classes and potentially capture those similarities with inheritance relation-
ships and hierarchies. The designers of the Java class libraries have followed these
principles, as we'll see when we examine a graphical subclass in this section.
However, there are also situations in which using inheritance seems like a good
choice but turns out to produce poor results. Misuse of inheritance can introduce
some pitfalls and problems that we'll now examine.
A Misuse of Inheritance
Imagine that you want to write a program that deals with points in three-dimensional
space, such as a three-dimensional game, rendering program, or simulation. A
Point3D class would be useful for storing the positions of objects in such a program.
This seems to be a case in which inheritance will be useful to extend the function-
ality of existing code. Many programmers would be tempted to have Point3D extend
Point and simply add the new code for the z -coordinate. Here's a quick implementa-
tion of a minimal Point3D class that extends Point :
1 // A Point3D object represents an (x, y, z) location.
2 // This is not a good design to follow.
3
4 public class Point3D extends Point {
5
private int z;
6
7 // constructs a new 3D point with the given coordinates
8
public Point3D( int x, int y, int z) {
 
 
Search WWH ::




Custom Search