Close
Close Window

MHC S25 COMSC 205: Data Structures

Chapter 4 Object Oriented Programming I: Inheritance

«  4.1. Introduction to Inheritance   ::   Contents   ::   5.1. Abstract Classes, Interfaces, and Polymorphism  »

4.2. Java’s Inheritance Mechanism

As we saw in the previous section, class inheritance is the mechanism whereby a class acquires (inherits) the methods and variables of its superclasses. To remind you of the general concept, let’s repeat the earlier example: just as horses inherit the attributes and behaviors associated with mammals and vertebrates, a Java subclass inherits the attributes and behaviors of its superclasses.

_images/jjj_horsehier.png

The diagram above illustrates 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 general attributes, such as being alive and being able to move. All animals share these attributes. The class of vertebrates is a somewhat more specialized 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, but it inherits the features of the classes above it.

4.2.1. 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 earlier. For example, 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:

 1public class Student {
 2    private String name;
 3
 4    public Student(String s) {
 5        name = s;
 6    }
 7    public String getName() {
 8        return name;
 9    }
10}

The figure below shows the relationship between this class and the Object class.

_images/jjj_student1.png

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:

1Student stu = new Student("Stu");
2System.out.println(stu.toString());

How does Java know where to find the toString() method, which, after all, is not defined in 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 () 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 executes that implementation of toString(). As you know from Chapter<nbsp/>3, this would result in the expression stu.toString() returning something like: Student@cde100.

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

Note

Try copying the code block below into a file called Student.java and running the program to see this happening!

 1public class Student {
 2    private String name;
 3    public Student(String s) {
 4        name = s;
 5    }
 6    public String getName() {
 7        return name;
 8    }
 9
10    public static void main(String[] args) {
11        Student stu = new Student("Stu");
12        System.out.println(stu.toString());
13    }
14}

4.2.2. Overriding an Inherited Method

In Section 4.1 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:

1public String toString() {
2return "My name is " + name +  " and I am a Student.";
3}
_images/jjj_student2.png

Given this change, the revised Student class hierarchy is shown in the Figure above. 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: My name is Stu and I am a Student..

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

Note

Try modifying the code from earlier with the new toString() method to see the result of the overriden method!

 1public class Student {
 2    private String name;
 3
 4    public Student(String s) {
 5        name = s;
 6    }
 7
 8    public String getName() {
 9        return name;
10    }
11
12    /** Overriden toString() method */
13    public String toString() {
14        return "My name is " + name +  " and I am a Student.";
15    }
16
17    public static void main(String[] args) {
18        Student stu = new Student("Stu");
19        System.out.println(stu.toString());
20    }
21}

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

Design principle: Inheritance. The public and protected instance methods (and variables) in a class can be used by objects that belong to the class’s subclasses.

Design principle: Overriding a Method. Overriding an inherited method is an effective way to customize that method for a particular subclass.

4.2.3. 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 correct 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 dynamic binding, when the JVM encounters a method call, it uses information 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 declaring a method as final means that the Java compiler can bind it to the correct implementation. Similarly, private methods are not inherited 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 run-time binding, leads to what is known 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).

Suppose we also have a Team class defined as follows:

 1public class Team {
 2    private String name;
 3    private String sport;
 4
 5    public Team (String name, String sport) {
 6        this.name = name;
 7        this.sport = sport;
 8    }
 9
10    public String toString() {
11        return "The " + name + " " + sport + " team.";
12    }
13}

Then the following simple example showcases polymorphism in action:

1Object obj;                        // Static type: Object
2obj = new Student("Stu");          // Actual type: Student
3System.out.println(obj.toString());// Prints "My name is Stu..."
4obj = new Team("MHC", "soccer");   // Actual type: Team
5System.out.println(obj.toString());// Prints "The MHC soccer team."

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 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 Team object to obj, thereby changing its actual type to Team. Thus, when obj.toString() is invoked in the last line, the toString() method is bound to the implementation found in the Team class.

Thus, we see that the same expression, obj.toString(), is bound alternatively to two different toString() implementations, based on the actual type of the object, obj, on which it is invoked. This is polymorphism and we will sometimes say that the `` toString()`` method is a polymorphic method. A polymorphic method is a method signature that behaves differently when it is invoked on different objects. An overridden method, such as the toString() method, is an example of a polymorphic method, because its use can lead to different behaviors depending upon the object on which it is invoked.

Let’s take an example where static binding, also called early binding, is not possible. Consider the following method definition:

1public void polyMethod(Object obj) {
2    System.out.println(obj.toString()); // Polymorphic
3}

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 following method calls in a program:

1Student stu = new Student("Stu");
2polyMethod(stu);
3Team tea = new Team("MHC", "soccer");
4polyMethod(tea);

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 second time polyMethod() is called, the obj.toString() expression is invoked on a Team object. In this case, Java will bind the method call to the implementation in the Team class. The output generated in this case will be tea’s toString() output: “The MHC soccer team.”

The important point here is that polymorphism occurs when an overridden 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 polymorphic because it is bound to different implementations of toString() depending on the actual type of the object that is bound to obj.

4.2.4. Using the super Keyword 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 concatenate the result of both the default and the new toString() methods. The following expression would accomplish that:

super.toString() + toString();

The super keyword specifies that the first toString() is the one implemented in the superclass. The second toString() refers simply to the version implemented within the Student class. We will see additional examples of using the super keyword in the following sections.

4.2.5. Inheritance and Constructors

Java’s inheritance mechanism applies to a class’s public and protected instance 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:

 1public class CollegeStudent extends Student {
 2    public CollegeStudent() { }
 3        public CollegeStudent(String s) {
 4        super(s);
 5    }
 6
 7    public String toString() {
 8        return "My name is " + name +
 9        " and I am a CollegeStudent.";
10    }
11}

Because CollegeStudent is a subclass of Student, it inherits the public and protected instance methods and variables from Student. So, a CollegeStudent has an instance variable for name and it has a public getName() method.

_images/jjj_collstudent.png

Note that CollegeStudent overrides the toString() method, giving it a more customized implementation. The hierarchical relationship between CollegeStudent and Student is shown in the figure above. A CollegeStudent is a Student and both are ``Object``s.

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 superclasses. However, if the subclass constructor does not explicitly invoke a superclass constructor, Java will automatically invoke the default superclass constructor – in this case, super().

By default superclass constructor 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 automatically call Student() and Object(). Note that if one of the superclasses 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 inherited 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:

1public B() {
2    A();   // Call the superconstructor
3    // Now continue with this constructor's code
4}

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

   «  4.1. Introduction to Inheritance   ::   Contents   ::   5.1. Abstract Classes, Interfaces, and Polymorphism  »

Close Window