11. Inheritance and Polymorphism

11.2. Java’s Inheritance Mechanism

As we described in Chapter 0, class inheritance is the mechanism whereby a class acquires (inherits) the methods and variables of its super- classes. To remind you of the basic concept, let’s repeat an earlier example: Just as horses inherit the attributes and behaviors associated with mam- mals and vertebrates, a Java subclass inherits the attributes and behaviors of its superclasses.

Figure 8.1 uses a UML diagram to illustrate the relationships among horses, mammals, vertebrates, and animals. As the root of the hierarchy, which is always shown at the top, the Animal class contains the most gen- eral attributes, such as being alive and being able to move. All animals share these attributes. The class of vertebrates is a somewhat more spe- cialized type of animal, in that vertebrates have backbones. Similarly, the class of mammals is a further specialization over the vertebrates in that

 

mammals are warm-blooded and nurse their young. Finally, the class of horses is a further specialization over the class of mammals, in that all horses have four legs. Some mammals, such as humans and penguins, do not have four legs. Thus, by virtue of its class’s position in this hierarchy, we can infer that a horse is a living, moving, four-legged vertebrate, which is warm blooded and nurses its young.

We have deliberately used an example from the natural world to show that the concept of inheritance in Java is inspired by its counterpart in the natural world. But how exactly does the concept of inheritance apply to Java (and to other object-oriented languages)? And, more importantly, how do we use the inheritance mechanism in object-oriented design?

Using an Inherited Method

In Java, the public and protected instance methods and instance variables of a superclass are inherited by all of its subclasses. This means that objects belonging to the subclasses can use the inherited variables and methods as their own.

We have already seen some examples of this in earlier chapters. For ex- ample, recall that by default all Java classes are subclasses of the Object class, which is the most general class in Java’s class hierarchy. One public method that is defined in the Object class is the toString() method. Because every class in the Java hierarchy is a subclass of Object, every class inherits the toString() method. Therefore, toString() can be used with any Java object.

To illustrate this, suppose we define a Student class as follows:

,,

 

 

 

 

 

 

 

 

Figure 8.2 shows the relationship between this class and the Object class. As a subclass of Object, the Student class inherits the toString() method. Therefore, for a given Student object, we can call its toString() as follows:

,


J

 

 

Figure 8.2: The Student class hi-

,erarchy.

 

 

J

How does this work? That is, how does Java know where to find the toString() method, which, after all, is not defined in the Student class? The answer to this question is crucial to understanding how Java’s inheritance mechanism works.

Note in this example that the variable stu is declared to be of type Student and is assigned an instance of the Student class. When the expression stu.toString() is executed, Java will first look in the

 

Student class for a definition of the toString() method. Not finding one there, it will then search up the Student class hierarchy (Fig. 8.2) until it finds a public or protected definition of the toString() method. In this case, it finds a toString() method in the Object class and it ex- ecutes that implementation of toString(). As you know from Chap- ter 3, this would result in the expression stu.toString() returning something like:

,,

 

J

The default implementation of toString() returns the name of the ob- ject’s class and the address (cde100) where the object is stored in mem- ory. However, this type of result is much too general and not particularly useful.

 

 

 

 

 

Overriding an Inherited Method

 

 

 

 

 

 

In Chapter 3 we pointed out that the toString() method is designed to be overridden—that is, to be redefined in subclasses of Object. Overriding toString() in a subclass provides a customized string representation of the objects in that subclass. We showed that by redefining toString() in our OneRowNim class, we customized its actions so that it returned useful information about the current state of a OneRowNim game.

To override toString() for the Student class, let’s add the following method definition to the Student class:

,,

 

Figure 8.3: The revised StudentJ

class hierarchy.Given this change, the revised Student class hierarchy is shown in Fig-

ure 8.3. Note that both Object and Student contain implementations of toString(). Now when the expression stu.toString() is invoked, the following, more informative, output is generated:

,,

 

J

In this case, when Java encounters the method call stu.toString(), it invokes the toString() method that it finds in the Student class (Fig. 8.3).

 

These examples illustrate two important object-oriented concepts: in- heritance and method overriding.

 

 

Static Binding, Dynamic Binding and Polymorphism

The mechanism that Java uses in these examples is known as dynamic binding, in which the association between a method call and the cor- rect method implementation is made at run time. In dynamic binding a method call is bound to the correct implementation of the method at run time by the Java Virtual Machine (JVM).

Dynamic binding is contrasted with static binding, the mechanism by which the Java compiler resolves the association between a method call and the correct method implementation when the program is compiled. In order for dynamic binding to work, the JVM needs to maintain some kind of representation of the Java class hierarchy, including classes defined by the programmer. When the JVM encounters a method call, it uses in- formation about the class hierarchy to bind the method call to the correct implementation of that method.

In Java, all method calls use dynamic binding except methods that are

declared final or private. Final methods cannot be overridden, so Dynamic binding

declaring a method as final means that the Java compiler can bind it to the correct implementation. Similarly, private methods are not inher- ited and therefore cannot be overridden in a subclass. In effect, private methods are final methods and the compiler can perform the binding at compile time.

Java’s dynamic-binding mechanism, which is also called late binding or Polymorphism run-time binding, leads to what is know as polymorphism. Polymorphism

is a feature of object-oriented languages whereby the same method call can lead to different behaviors depending on the type of object on which the method call is made. The term polymorphism means, literally, having many (poly) shapes (morphs). Here’s a simple example:

,,

 

 

 

J

The variable obj is declared to be of type Object. This is its static or

declared type. A variable’s static type never changes. However, a variable

 

 

 

 

 

 

 

 

 

 

 

 

 

Polymorphic method


also has an actual or dynamic type. This is the actual type of the object that has been assigned to the variable. As you know, an Object variable can be assigned objects from any Object subclass. In the second statement, obj is assigned a Student object. Thus, at this point in the program, the actual type of the variable obj is Student. When obj.toString() is invoked in the third line, Java begins its search for the toString() method at the Student class, because that is the variable’s actual type.

In the fourth line, we assign a OneRowNim object to obj, thereby chang- ing its actual type to OneRowNim. Thus, when obj.toString() is in- voked in the last line, the toString() method is bound to the imple- mentation found in the OneRowNim class.

Thus, we see that the same expression, obj.toString(), is bound al- ternatively to two different toString() implementations, based on the actual type of the object, obj, on which it is invoked. This is polymor- phism and we will sometimes say that the toString() method is a poly- morphic method. A polymorphic method is a method signature that be- haves differently when it is invoked on different objects. An overridden method, such as the toString() method, is an example of a polymor- phic method, because its use can lead to different behaviors depending upon the object on which it is invoked.

The previous example is admittedly somewhat contrived. In some object-oriented languages, a code segment such as that above would use static binding rather than dynamic binding. In other words, the com- piler would be able to figure out the bindings. So let’s take an example where static binding, also called early binding, is not possible. Consider the following method definition:

,,

 

 

 

J

The method call in this method, obj.toString(), can’t be bound to the correct implementation of toString() until the method is actually invoked—that is, at run time. For example, suppose we make the follow- ing method calls in a program:

,,

 

 

 

J

The first time polyMethod() is called, the obj.toString() is invoked on a Student object. Java will use its dynamic binding mechanism to associate this method call with the toString() implementation in Student and output “My name is Stu and I am a Student.” The sec- ond time polyMethod() is called, the obj.toString() expression is invoked on a OneRowNim object. In this case, Java will bind the method call to the implementation in the OneRowNim class. The output generated in this case will report how many sticks are left in the game.

 

The important point here is that polymorphism occurs when an over- ridden method is called on a superclass variable, obj. In such a case, the actual method implementation that is invoked is determined at run time. The determination depends on the type of object that was assigned to the variable. Thus, we say that the method call obj.toString() is poly- morphic because it is bound to different implementations of toString() depending on the actual type of the object that is bound to obj.

 

 

 

 

Polymorphism and Object-Oriented Design

 

 

 

Now that we understand how inheritance and polymorphism work in Java, it will be useful to consider an example that illustrates how these mechanisms can be useful in designing classes and meth- ods. We have been using the various System.out.print() and System.out.println() methods since Chapter 1. The print() and println() methods are examples of overloaded methods—that is,

methods that have the same name but different parameter lists. Remem- Overloaded methods

ber that a method’s signature involves its name, plus the type, num- ber, and order of its parameters. Methods that have the same name but different parameters are said to be overloaded.

Here are the signatures of some of the different print() and

println() methods:

,,

 

 

 

 

J

Basically, there is a print() and println() method for every type of primitive data, plus methods for printing any type of object. When Java encounters an expression involving print() or println() it chooses which particular print() or println() method to call. To determine the correct method, Java relies on the differences in the signatures of the various print() methods. For example, because its argument is an int, the expression print(5) is associated with the method whose signature is print(int i) be cause its parameter is an int.

Note that there is only one set of print() and println() meth- ods for printing Objects. The reason is that polymorphism is used by the print(Object o) and println(Object o) methods to print any type of object. While we do not have access to the source code for these

 

methods, we can make an educated guess that their implementations utilize the polymorphic toString() method, as follows:

,,

 

 

 

 

 

J

Here again we have a case where an expression, o.toString(),

 

 

 

 

 

 

 

Extensibility


is bound dynamically to the correct implementation of toString() based on the type of Object that the variable o is bound to. If we call System.out.print(stu), where stu is a Student, then the Student.toString() method is invoked. On the other hand, if we call System.out.print(game), where game is a OneRowNim, then the OneRowNim.toString() method is invoked.

The beauty of using polymorphism in this way is the flexibility and

extensibility that it allows. The print() and println() methods can print any type of object, even new types of objects that did not exist when these library methods were written.

 

SELF-STUDY EXERCISES

EXERCISE 8.1 To confirm that the print() and println() methods are implemented along the lines that we suggest here, compile and run the TestPrint program shown here. Describe how it confirms our claim.

,,

 

 

 

 

 

J

EXERCISE 8.2 Override the toString() method in the TestPrint class and rerun the experiment. Describe how this adds further confirma- tion to our claim.

Using super to Refer to the Superclass

One question that might occur to you is: Once you override the default toString() method, is it then impossible to invoke the default method on a Student object? The default toString() method (and any method from an object’s superclass) can be invoked using the super keyword. For example, suppose that within the Student class, you wanted to concate- nate the result of both the default and the new toString() methods. The following expression would accomplish that:

,,

 

J

 

The super keyword specifies that the first toString() is the one imple- mented in the superclass. The second toString() refers simply to the

version implemented within the Student class. We will see additionalKeyword super

examples of using the super keyword in the following sections.

 

 

 

 

SELF-STUDY EXERCISES

 

EXERCISE 8.3Consider the following class definitions and determine the output that would be generated by the code segment.

,,

 

 

 

 

 

 

 

 

 

 

J

 

 

EXERCISE 8.4 For the class B defined in the previous exercise, modify its method() so that it invokes A’s version of method() before printing out B.

 

 

EXERCISE 8.5 Given the definitions of the classes A and B, which of the following statements are valid? Explain.

,,

 

 

 

J

 

Inheritance and Constructors

Java’s inheritance mechanism applies to a class’s public and protected in- stance variables and methods. It does not apply to a class’s constructors.

 

To illustrate some of the implications of this language feature, let’s define a subclass of Student called CollegeStudent:

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 8.4: The class hierarchy for

CollegeStudent .

 

 

 

 

Constructor chaining


J

Because CollegeStudent is a subclass of Student, it inherits the pub- lic and protected instance methods and variables from Student. So, a CollegeStudent has an instance variable for name and it has a public getName() method. Recall that a protected element, such as the name variable in the Student class, is accessible only within the class and its subclasses. Unlike public elements, it is not accessible to other classes.

Note that CollegeStudent overrides the toString() method, giv-

ing it a more customized implementation. The hierarchical relationship between CollegeStudent and Student is shown in Figure 8.4. A CollegeStudent is a Student and both are Objects.

Note how we have implemented the CollegeStudent(String s) constructor. Because the superclass’s constructors are not inherited, we have to implement this constructor in the subclass if we want to be able to assign a CollegeStudent’s name during object construction. The method call, super(s), is used to invoke the superclass constructor and pass it s, the student’s name. The superclass constructor will then assign s to the name variable.

As we have noted, a subclass does not inherit constructors from its su-

perclasses. However, if the subclass constructor does not explicitly invoke a superclass constructor, Java will automatically invoke the default su- perclass constructor—in this case, super(). By “default superclass con- structor” we mean the constructor that has no parameters. For a subclass that is several layers down in the hierarchy, this automatic invoking of the super() constructor will be repeated upwards through the entire class hierarchy. Thus when a CollegeStudent is constructed, Java will auto- matically call Student() and Object(). Note that if one of the super- classes does not contain a default constructor, this will result in a syntax error.

If you think about this, it makes good sense. How else will the in- herited elements of the object be created? For example, in order for a CollegeStudent to have a name variable, a Student object, where name is declared, must be created. The CollegeStudent constructor then extends the definition of the Student class. Similarly, in order for a Student object to have the attributes common to all objects, an Object instance must be created and then extended into a Student.

Thus, unless a constructor explicitly calls a superclass constructor, Java

will automatically invoke the default superclass constructors. It does this

 

before executing the code in its own constructor. For example, if you had two classes, A and B, where B is a subclass of A, then whenever you create an instance of B, Java will first invoke A’s constructor before executing the code in B’s constructor. Thus, Java’s default behavior during construction of B is equivalent to the following implementation of B’s constructor:

,,

 

 

 

J

Calls to the default constructors are made all the way up the class hierar- chy, and the superclass constructor is always called before the code in the class’s constructor is executed.

 

SELF-STUDY EXERCISES

EXERCISE 8.6 Consider the following class definitions and describe what would be output by the code segment.

,,

 

 

 

 

 

 

 

 

 

 

J