Object-Oriented Programming with Java · Lecture Notes

Chapter 4.3: Inheritance

Real programs are full of classes that look alike. A student and a teacher both have a name and an age; a cat, a dog and a bird all eat, sleep and make a sound. Rewriting the shared part in every class costs effort and invites bugs: a fix made in one place is forgotten in another. Inheritance solves this. The shared fields and methods are written once, in a superclass; subclasses receive them by inheritance and add only what makes them different. These notes first explain what inheritance is, the extends syntax, and what a subclass receives. They then follow the super keyword, the constructor chain and the order of initialization step by step. Method overriding and its rules, protected access, and limiting inheritance with final come next. The last sections cover the is-a and has-a relationships between classes, the design traps of inheritance, and the toString, equals and hashCode methods of Object, the ancestor of every class.

Learning outcomes

Concept
Define inheritance, superclass and subclass; recognize the is-a relationship.
Syntax
Write a subclass with extends; explain what is inherited and what is not.
Constructors
Use super(...) and super.method(); trace the order in which constructors and initialization run.
Overriding
Override a method, tell overriding from overloading, use @Override, and explain the reasons behind the rules.
Access and restriction
Explain protected access and how final restricts inheritance.
Design
Choose between inheritance and composition; recognize the fragile base class problem and violations of the substitution principle.
The Object class
Write toString, equals and hashCode correctly; know the difference between == and equals.

4.3.1The concept of inheritance

A class is a template for objects of the same structure: it says what data they hold and what they can do. In a real program, classes do not stand apart. Some are more specific forms of others. Every rectangle is a shape, every student is a person, every cat is an animal. Inheritance turns this “more specific form of” relationship between classes into code. This section defines inheritance, gives the syntax in Java, explains what a subclass receives, and shows how a subclass object is laid out in memory.

4.3.1.1What is inheritance?

Definition 4.3.1

Inheritance is creating a new class by taking the fields and methods of an existing class and enriching them with new or modified capabilities. The existing class is called the superclass, the new class the subclass.

Two verbs in the definition matter: taking and enriching. A subclass takes the fields and methods of its superclass without rewriting them. The inherited members are not defined again in the subclass; they are used as if they were its own. On top of these, the subclass can add new fields and new methods. It can also change the behavior of a method it took from the superclass.

An everyday sentence sums up the relationship: “Every rectangle is a shape.” In a drawing program every shape has a color and every shape can be drawn. A rectangle has all of these common properties. On top of them it has its own width and height, and its area is computed from the two. The relationship can also be shown in a diagram. Figure 4.3.1 shows it as a UML (Unified Modeling Language) class diagram.

superclassShape- color : String+ draw() : voidextendsRectangle- width : double- height : double+ area() : doublesubclass
Figure 4.3.1: Class Rectangle derives from class Shape. In UML, inheritance is drawn as an arrow with a hollow triangle head pointing at the superclass. The subclass box lists only the members the subclass adds itself; color and draw() arrive by inheritance.

In the diagram, the Rectangle box has no color field and no draw() method. They have not been written there, yet every Rectangle object has them. That is exactly what inheritance means: the shared part is written once, in the superclass, and each subclass carries only its own difference. A reader following the arrow forms the sentence “a Rectangle is a Shape”. The direction of the arrow is the direction of that sentence.

4.3.1.2A subclass with extends

In Java, the fact that a class derives from another class is declared with the extends keyword. The syntax is class SubClass extends SuperClass. The subclass extends the superclass; that is what the word means.

// base class (superclass)
public class Shape {
    // fields and methods of the base class
    // ...
}

// new class (subclass), derived from Shape
public class Rectangle extends Shape {
    // fields and methods of the new class
    // ...
}

The bodies of these two classes are still empty, but the relationship is established. Every object of type Rectangle is now a Shape. Every public and protected member later added to Shape can be used in Rectangle as well. The subclass code calls these members as if they were its own, with no object name or prefix.

Only one class may follow extends. Java does not allow multiple inheritance of classes. A class that never writes extends still has a superclass: the compiler quietly derives it from java.lang.Object. Figure 4.3.2 shows this two-step chain.

RectanglesubclassShapesuperclassObjectimplicit superclassextendsextends
Figure 4.3.2: Rectangle extends Shape explicitly. Because Shape does not write extends, the compiler derives it from Object. The chain always ends at Object.

There is one more thing a subclass should not do. If a field with the same name as a superclass field is declared again in the subclass, Java does not complain. But the two fields are not the same variable. The object holds two separate variables; the subclass code sees its own field and the superclass code sees its own. This is called field hiding. It is hard to follow which code reads which value, and the bugs appear silently. A field that arrives by inheritance is not declared again in the subclass.

Common mistake

Adding String color to the subclass when the superclass already has String color. The subclass constructor writes color = "red", but the superclass's draw() method reads its own color field and sees null. The right way is to keep the field only in the superclass and set its value through the superclass constructor.

4.3.1.3Subclass and superclass: specialization

A subclass exhibits all the behaviors of its superclass. In addition, it can exhibit behaviors of its own. A cat does everything an animal does: it eats, sleeps and breathes. It also meows and climbs. This is why inheritance is also called specialization. The subclass represents a more specific group within the group the superclass represents.

The relationship is one-directional. Every cat is an animal, but not every animal is a cat. In code the consequence is clear. A Cat object can be assigned to a variable of type Animal, because a cat can do everything expected of an animal. The reverse is not allowed. A plain Animal object cannot be assigned to a Cat variable; nothing says that object can meow.

ObjectAnimalStringShapeCatDogRectangleup: general · down: specific
Figure 4.3.3: A small part of the Java class hierarchy. Object is at the top. Going up, classes become more general; going down, more specific.

Java's class hierarchy starts with the Object class in package java.lang. Figure 4.3.3 shows a slice of it. Animal, String and Shape derive directly from Object; Cat and Dog derive from it indirectly, through Animal. Every class inherits from Object, directly or indirectly. That is why the methods of Object are available on every object.

4.3.1.4Kinds of inheritance

Inheritance relationships between classes can be arranged in four ways. Figure 4.3.4 shows all four side by side.

SingleMultilevelHierarchicalMultiple (not for classes)AnimalCatLivingThingAnimalCatAnimalCatDogBirdBCD✗provided by interfaces
Figure 4.3.4: Kinds of inheritance. Single, multilevel and hierarchical inheritance exist in Java. Multiple inheritance, where a class has two superclasses, does not exist for classes; interfaces meet the same need.
  • In single inheritance there is one subclass and its one superclass: Cat extends Animal.
  • In multilevel inheritance the classes form a chain: Animal extends LivingThing and Cat extends Animal. Cat receives the members of LivingThing through Animal. Each level carries everything from the one before.
  • In hierarchical inheritance many subclasses derive from one superclass: Cat, Dog and Bird all derive from Animal. The shared code is written once; each subclass adds only its own difference.
  • In multiple inheritance a class has more than one superclass. Java does not allow this for classes. Interfaces meet the same need: a class can extend a single class while implementing many interfaces.

As a consequence of these rules, the class hierarchy in Java is a tree. The root of the tree is Object. Every class other than Object has exactly one direct superclass. There is no limit on the depth of a chain. But deep chains make code harder to read and change: to understand the behavior of one class, you must look at all the classes above it. In practice, hierarchies deeper than two or three levels are built only for good reason.

4.3.1.5What is inherited?

The sentence “a subclass takes everything from its superclass” is only partly true. The true part is this: inside a subclass object, all the fields of the superclass are present. But whether the code of the subclass may reach those fields and methods directly is decided by the access modifier. Constructors are never inherited. Table 4.3.1 summarizes the situation by kind of member.

Table 4.3.1: Are the members of the superclass passed on to the subclass?
MemberPassed to the subclass?Note
public / protected fields and methodsYesUsed directly in the subclass.
Members with no modifier (package access)Only if in the same packageA subclass in another package cannot access them.
private fieldsPresent in the object, but not directly accessibleUsed through the superclass's public / protected methods (getters, setters).
private methodsNoInvisible; cannot be overridden.
ConstructorsNoA subclass constructor calls the superclass's with super(...).
static membersAccessibleThey belong to the class; they are not overridden, only hidden.

The row of the table that is most often confused is the one for private fields. Suppose Animal has a private double health field. When Cat extends Animal is written, every Cat object contains a health field. When the cat sleeps, its health rises and the value is stored in this field. But if the code of class Cat writes health += 5, the compiler reports an error with the message health has private access in Animal. The field is there, but access by name is open only to the code of Animal itself. Cat reaches the field through the methods Animal offers.

There is a good reason constructors are not inherited either. A constructor's name is the name of its class. If the constructor Animal(String name) were passed on to Cat, the call new Cat("Mavi") would set up only the Animal part, and Cat's own fields would be left unset. So every class writes its own constructor. The subclass constructor calls the superclass constructor with super(...) so that the superclass part gets set up.

Example 4.3.1

Let class Animal have these members: private String name, protected int age, a package-private void eat(), public String getName() and private void digest(). Cat extends Animal is written in another package.

In the code of Cat, age (protected) and getName() (public) are used directly. name exists in the object, but it can be reached only through getName(). eat() is package-private, and since Cat is in another package, it is invisible. digest() is private and never visible. Had Cat been a class in the same package, eat() could have been used too.

4.3.1.6The structure of a subclass object

People who are new to inheritance often form this picture: writing new Cat(...) creates a Cat object and, inside it or next to it, an Animal object. That picture is wrong. new Cat(...) creates a single object. No separate object is created for the superclass.

Stackmain()kHeap: a single objectCat objectObject partAnimal part- name = "Mavi"- health = 100.0Cat part- indoor = truethis and super are the same object
Figure 4.3.5: A Cat object. The Object, Animal and Cat parts are inside the same object. The variable k on the stack points to this single object. this and super look at the same object.

Figure 4.3.5 shows the inside of the object. The object is made of layers. The innermost layer is the part that comes from Object. Above it sit the fields of Animal (name, health), and on top is Cat's own field (indoor). Even when the fields of Animal are private, they are inside this object. Only the code of Cat cannot reach them by name.

In this picture the super keyword does not point to a separate object. super is a way of reaching the superclass part of the same object through the superclass's code. this and super carry the same address; the difference lies in which class's method gets called. This distinction is the key to understanding the constructor chain and overriding.

There is a proof of this. The getClass() method of Object returns the actual runtime class of the object. In the following program the getClass() call is inside the constructor of Animal:

class Animal {
    Animal() {
        System.out.println("In Animal(): "
            + getClass().getSimpleName());
    }
}
class Cat extends Animal { }
// in main:
new Cat();
new Animal();
In Animal(): Cat
In Animal(): Animal

The first line may look surprising. The code that runs is the constructor of Animal, yet the object's class comes out as Cat. The reason is this: new Cat() first reserves space for a Cat object and then sets up the parts of this object in order. While Animal() runs, what it sets up is the Animal part of a Cat. There is no separate Animal object. On the second line, new Animal() really does create an Animal object. No constructor is written in class Cat; the compiler adds a no-argument default constructor to it, and this constructor calls Animal().

4.3.1.7Moving shared code up to the superclass

Inheritance is often not set up at the start of a design. A few classes are written first, and later repeated code is noticed among them. Finding this repetition and moving it into a common superclass is called generalization. Generalization is the reverse of specialization. In specialization you go down from a general class to a specific one; in generalization you go up from specific classes to a common general one.

Suppose a school management program starts with these two classes:

class Student {
    private String name;
    private int age;
    private double gpa;
    String info() { return name + " (" + age + ")"; }
}
class Teacher {
    private String name;
    private int age;
    private String subject;
    String info() { return name + " (" + age + ")"; }
}

In both classes the fields name and age and the method info() are exactly the same. The price of this repetition is paid when something changes. Say the display format of the age changes, for example “20 years old” instead of “(20)”. Both classes must be fixed. If one is forgotten, the program prints the same information in two different formats. The more classes there are, the more likely a class is forgotten.

Once the shared part is moved to a Person class, the code looks like this:

class Person {
    private String name;
    private int age;
    Person(String name, int age) { this.name = name; this.age = age; }
    String info() { return name + " (" + age + ")"; }
}
class Student extends Person {
    private double gpa;
    Student(String name, int age, double gpa) {
        super(name, age);
        this.gpa = gpa;
    }
    @Override String info() {
        return super.info() + ", gpa " + gpa;
    }
}   // Teacher likewise: adds subject

Student now carries only its own difference: the gpa field. It does not store the name and age itself; in its constructor it passes them to the constructor of Person with super(name, age). It overrides info() but does not rewrite the shared part: with super.info() it calls the version of Person and appends the grade average. Teacher is written the same way: its field is subject, and it appends the subject to the end of info(). When the program runs, two lines are printed:

Ece (20), gpa 3.4
Murat (41), Physics

Now the display format of the age changes in a single place, Person.info(); both subclasses use the new format automatically.

Before generalizing, ask a question: “Is every student a person?” If the answer is yes, generalization is right. If only a few fields of two classes look alike and there is no “is a kind of” relationship between them, inheritance is the wrong tool. For example, a Student and a Course may both have a name field. But a course is not a student. In such cases the shared code goes into a separate helper class and is used through composition.

Example 4.3.2

Suppose an electric circuit simulation program has classes Resistor, Capacitor and Inductor. In all three, two node numbers (nodeA, nodeB), a name and a method connect(int a, int b) are repeated. Each one's own value differs: resistance, capacitance and inductance.

The answer to “is every resistor a circuit element?” is yes, and the same holds for the other two. The shared fields and the connect method move up into a CircuitElement superclass. Each subclass keeps only its own value and the computation that depends on it, for example an impedance(double frequency) method. If the checking of node numbers changes, only CircuitElement needs fixing.

4.3.2The animal example

The parts of inheritance are easier to understand when they are seen together in one example. This section builds an animal hierarchy. The shared members are collected in a superclass; the subclasses change one behavior and add behavior of their own.

4.3.2.1The animal class hierarchy

Animal- name : String- age : int- health : double+ getName() : String+ speak() : void+ eat(double) : void+ sleep() : void+ toString() : StringCat+ speak() : void+ hunt() : voidDog+ speak() : void+ playBall() : voidBird+ speak() : void+ fly() : voidHorse+ speak() : void+ run() : void
Figure 4.3.6: The classes Cat, Dog, Bird and Horse derive from Animal. Each overrides speak() in its own way and adds a method of its own. The - sign marks a private member, the + sign a public one.

Figure 4.3.6 is a typical example of hierarchical inheritance. Class Animal carries the fields common to all animals: name, age, health. The common behaviors are written in it too: speak, eat, sleep, toString. These members are written once, in Animal. The boxes of the four subclasses hold only two methods. One is speak(); since every animal makes a different sound, each subclass rewrites this method its own way. The other is a behavior specific to that animal: the cat hunts, the dog plays ball, the bird flies, the horse runs.

The diagram yields one more conclusion. Adding a new kind of animal does not require touching Animal. For example, a Cow class derives from Animal, overrides speak() and adds a milk() method. Sleeping, eating and health tracking come for free.

4.3.2.2Classes Animal and Dog

The code of the hierarchy starts with two classes. The superclass Animal holds the fields and behaviors common to all animals:

public class Animal {
    private String name;     // common fields
    private int age;
    private double health;

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
        this.health = 100.0;
    }
    public String getName() { return name; }   // access to private name
    public void speak() {
        System.out.println("This animal speaks.");
    }
    public void sleep() {
        health += 5;
        System.out.println(name + " slept. Health: " + health);
    }
}

All three fields are private. They cannot be reached directly from outside or from subclasses. The way to reach name is the getName() method. The constructor takes two values and starts health at 100. speak() prints a generic message; how a particular animal speaks is not yet known. sleep() raises health by 5 and prints the state.

The subclass Dog writes only the difference:

public class Dog extends Animal {
    public Dog(String name, int age) {
        super(name, age);   // superclass sets the fields
    }
    @Override
    public void speak() {   // changes inherited behavior
        System.out.println(getName() + " barks.");
    }
    public void playBall() { // behavior only Dog has
        System.out.println(getName() + " is playing ball!");
    }
}

The class does three things. Its constructor passes the name and age it receives to the constructor of Animal with super(name, age); Animal fills in the fields. It overrides speak(): the @Override annotation states that this method rewrites a method that came from the superclass. Finally it adds the method playBall(), which only dogs have. Note that the code of Dog never touches the name field directly; it gets the name with getName(). Since name is private, there is no other way.

Dog dog = new Dog("Karabaş", 4);
dog.speak();     // Dog's version
dog.playBall();   // Dog only
dog.sleep();       // inherited from Animal
Karabaş barks.
Karabaş is playing ball!
Karabaş slept. Health: 105.0

The three calls show three different situations. dog.speak() runs the version that Dog overrides; “This animal speaks.” is not printed. dog.playBall() is a method only Dog has. dog.sleep() is not written in Dog at all. Java looks for this method in Dog first, and when it does not find it, goes up one level to Animal and finds it there. The method is the code of Animal, yet it raises the health field of this dog object from 100 to 105.

The method lookup rule is the basic mechanism of inheritance. When a method is called on an object, the search starts at the object's actual class. If the method is not there, the search climbs the hierarchy. The first version found runs. A method that is not found even in Object is rejected by the compiler anyway.

4.3.2.3The advantages of inheritance

Inheritance has three benefits.

  • Reuse. The methods and fields of the superclass are used in the subclass without being rewritten. The shared code lives in one place; a fix reaches all subclasses.
  • Extension. An existing class is extended with new capabilities without changing its code. The superclass may belong to another team or to a library; there is no need to touch its source.
  • Modification. The methods of the superclass can be changed by overriding them in the subclass. The subclass rewrites only the part of the shared behavior that does not suit it.

A calculator gives an example of extension. Suppose we have a class Calculator that does the four operations and keeps the last result in a memory field. The slides show this class only as a diagram; it can be written like this:

class Calculator {
    private double memory;
    public double add(int a, int b) { memory = a + b; return memory; }
    public double multiply(int a, int b) { memory = a * b; return memory; }
    public double showMemory() { return memory; }
}
Calculator- memory : double+ add(int, int) : double+ multiply(int, int) : double+ showMemory() : doubleAdvancedCalculator+ pow(double, int) : double+ factorial(int) : long
Figure 4.3.7: AdvancedCalculator derives from Calculator and adds the methods pow and factorial. The code of the superclass does not change.

Suppose a user who needs scientific calculation wants exponentiation and factorial added. Figure 4.3.7 shows the solution. The new class extends the old one; the four operations and the memory come for free:

public class AdvancedCalculator
        extends Calculator {
    // new ability: exponentiation
    public double pow(double base, int pow) {
        double result = 1.0;
        for (int i = 0; i < pow; i++) {
            result *= base;
        }
        return result;
    }
    // factorial(int) is added likewise
}
// in main
AdvancedCalculator h = new AdvancedCalculator();
System.out.println(h.add(5, 3));         // 8.0  (inherited)
System.out.println(h.showMemory()); // 8.0  (inherited)
System.out.println(h.pow(2, 5));            // 32.0 (new)
8.0
8.0
32.0

The calls h.add(5, 3) and h.showMemory() are not written in AdvancedCalculator; both come by inheritance and give 8.0. pow(2, 5) is the new method. The loop runs five times and result becomes 2, 4, 8, 16, 32 in turn. It is no problem in Java that the parameter pow has the same name as the method: method names and variable names live in separate namespaces. For readability, it is still better to choose different names.

In terms of cost, calling a method that arrives by inheritance costs the same as calling a method of the class itself. The Java virtual machine keeps a method table for each class. A lookup amounts to reading one entry in the table; the depth of the hierarchy is not rescanned at every call. So the real price of inheritance is paid not at run time but in design. That price is tight coupling between classes.

4.3.3Constructors and super

When a subclass object is built, its superclass part must be built as well. Giving initial values to the superclass's fields is the superclass's job. This section describes the tool for this cooperation between subclass and superclass, the super keyword. It then shows the order in which constructors run, step by step, with three code traces.

4.3.3.1The super keyword

Definition 4.3.2

super is the keyword that refers to the superclass inside the subclass's code. It is used in two forms. super(...) calls the superclass constructor from inside the subclass constructor. super.method() calls a version of a method in the superclass; it is usually used from inside an overridden method.

There are two rules about super(...). First, super(...) must be the first statement of the constructor. This rule holds in all widely used versions, including Java 21. Java 25 relaxes it a little: statements that do not touch the object under construction may appear before super(...). For example, the parameters can be checked. But these notes take Java 21 as the baseline. Second, if a constructor writes neither super(...) nor this(...), the compiler quietly inserts super();. So a superclass constructor is always called; the programmer's only choice is which one.

A design principle lies behind these rules: each class manages only its own data. Cat does not assign Animal's name field itself; it leaves the job to super(name). Animal is the class that knows best how its own fields should be initialized. Perhaps it checks that the name is not empty, perhaps it starts health at 100. The subclass need not know these rules.

class Cat extends Animal {
    private boolean indoor;

    Cat(String name, boolean indoor) {
        super(name);         // Animal(String)
        this.indoor = indoor;  // its own data
    }

    @Override
    public String toString() {
        return super.toString()   // Animal's
               + ", Indoor: " + indoor;
    }
}
// in main
System.out.println(new Cat("Mavi", true));
Name: Mavi, Health: 100.0, Indoor: true

Here the constructor Animal(String name) writes the name to its field and sets health to 100.0. The toString() method of Animal returns the name and health as "Name: Mavi, Health: 100.0". The constructor of Cat calls this constructor with super(name) on its first line, then fills its own field indoor. The toString() of Cat does not reproduce the text the superclass makes. It gets that text with super.toString() and appends only its own field. println calls the toString() method of the object it is given. Since the object is a Cat, the version in Cat runs.

This pattern is very common: the overriding method first has the superclass do its work with super, then adds its own difference. That way, when the behavior of the superclass changes, for example when Animal.toString() starts printing the age as well, the output of Cat updates by itself.

4.3.3.2Code trace: the super.introduce() chain

Calls of super.method() can also be chained. In a three-level hierarchy, let each class override introduce() and let each call its superclass's version first:

class LivingThing {
    void introduce() { System.out.println("I'm alive"); }
}
class Animal extends LivingThing {
    void introduce() {
        super.introduce();
        System.out.println("I'm an animal");
    }
}
class Cat extends Animal {
    void introduce() {
        super.introduce();
        System.out.println("I'm a cat");
    }
}
new Cat().introduce();   // main
I'm alive
I'm an animal
I'm a cat

At first glance the order of the output looks reversed. The call starts at Cat, yet the first line printed is LivingThing's. Table 4.3.2 traces the calls step by step.

Table 4.3.2: Trace of the call new Cat().introduce(). In the stack column the topmost frame is on the right.
StepEventCall stackOutput
1The object is a Cat; the search starts at the bottom, and Cat.introduce() is found.main, Cat.introduce—
2super.introduce(): Animal.introduce() is called. Cat.introduce waits.main, Cat.introduce, Animal.introduce—
3The super inside Animal points fixedly to LivingThing: LivingThing.introduce().main, Cat.introduce, Animal.introduce, LivingThing.introduce—
4The topmost version prints and returns.main, Cat.introduce, Animal.introduceI'm alive
5Animal.introduce() resumes where it left off, prints and returns.main, Cat.introduceI'm an animal
6Cat.introduce() prints its own line and returns.mainI'm a cat
LivingThingintroduce()Animalintroduce()Catintroduce()Call stackCat.introduce()main()object: Cat #1the search starts at the actual class: Cat.introduce() LivingThingintroduce()Animalintroduce()Catintroduce()supersuperCall stackLivingThing.introduce()Animal.introduce()Cat.introduce()main()object: Cat #1 LivingThingintroduce()Animalintroduce()Catintroduce()Call stackLivingThing.introduce()Animal.introduce()Cat.introduce()main()object: Cat #1I'm alive is printed, LivingThing.introduce() returns LivingThingintroduce()Animalintroduce()Catintroduce()Call stackmain()object: Cat #1calls go bottom to top, output goes top to bottom
Figure 4.3.8: Four moments of the super.introduce() chain. (a) Cat.introduce() runs. (b) Two super calls push Animal.introduce and LivingThing.introduce onto the stack. (c) LivingThing prints the first line. (d) All the calls have returned; the outputs came in reverse order.

The third step carries a subtle point. The object is still a Cat. In an ordinary method call the search starts from the object's actual class. If this rule were followed, the call inside Animal would go to Cat.introduce() again and an infinite loop would result. super does not follow this rule. The super written in the code of Animal always points to the superclass of Animal, that is LivingThing, whatever the class of the object is. This link is fixed at compile time; it is not chosen at run time by looking at the object.

Figure 4.3.8 shows the general form of the chain. The calls go in the direction Cat → Animal → LivingThing, and the outputs come in reverse order. Each class first has the superclass do its work, then adds its own difference. The stack reaches at most four frames: main and three introduce frames. Each level of the chain adds one call and one frame. So for a chain of d levels, the running time and the stack use are proportional to d, that is O(d). Had new Animal().introduce() been called, the chain would be one level shorter and only “I'm alive” and “I'm an animal” would be printed.

4.3.3.3Code trace: the constructor chain

Constructors form a similar chain. In the code below, the constructor of Animal writes super() explicitly. Had it not, the compiler would have inserted the same line itself.

class Animal {
    private String name;
    private double health;
    Animal(String name) {
        super();   // Object() is called
        this.name = name;
        health = 100.0;
        System.out.println("Animal constructor");
    }
}
class Cat extends Animal {
    private boolean indoor;
    Cat(String name, boolean indoor) {
        super(name);
        this.indoor = indoor;
        System.out.println("Cat constructor");
    }
}
// in main
Cat cat = new Cat("Mavi", true);
System.out.println("Object ready");
Animal constructor
Cat constructor
Object ready

The evaluation of the expression new Cat("Mavi", true) can be examined in eleven steps. Table 4.3.3 gives these steps together with the current values of the object's fields.

Table 4.3.3: Trace of new Cat("Mavi", true). The fields are, in order, name, health and indoor.
StepCode runningnamehealthindoorOutput
1new: space is reserved for the objectnull0.0false
2Cat(...) is callednull0.0false
3super(name): Animal(...); Cat waitsnull0.0false
4super(): Object()null0.0false
5Object() returned; this.name = name"Mavi"0.0false
6health = 100.0"Mavi"100.0false
7Animal prints and returns"Mavi"100.0falseAnimal constructor
8Cat resumes: this.indoor = indoor"Mavi"100.0true
9Cat prints"Mavi"100.0trueCat constructor
10The object's address is assigned to cat"Mavi"100.0true
11main resumes"Mavi"100.0trueObject ready
cat—Cat objectfrom AnimalCat's ownname = nullhealth = 0.0indoor = false cat—Cat objectfrom AnimalCat's ownname = "Mavi"health = 100.0indoor = false cat—Cat objectfrom AnimalCat's ownname = "Mavi"health = 100.0indoor = true catCat objectfrom AnimalCat's ownname = "Mavi"health = 100.0indoor = true
Figure 4.3.9: Four moments of the constructor chain. (a) new reserved space for the object; all fields hold default values. (b) Animal filled in its own fields. (c) Cat filled in its own field. (d) The address of the object was assigned to the variable cat.

The first step of the trace is important. new reserves space for all the fields of the object before any constructor runs. The name and health that come from Animal are included. All fields take their default values: references null, numbers 0, boolean false. The first frame of Figure 4.3.9 shows this state. Constructors do not create fields; they only write values into existing fields.

Then the calls go from the bottom up: Cat → Animal → Object. Since each constructor first calls the constructor of its superclass, none of them can get to its body and all wait. The chain always ends at Object. Object() has no superclass and its body is empty; it returns at once. After that the bodies complete from the top down: first Animal fills in its own fields and prints its message, then Cat. The result can be said in one sentence: constructors complete from the top down, Object → Animal → Cat.

There is a reason for this order. The constructor of a subclass must be able to use the fields and methods that come from the superclass. For example, the constructor of Cat may want to call getName() and print a message. For that to be safe, the Animal part must already be built. Completing the superclass first guarantees this.

In the last step the object is ready and its address is assigned to the variable cat. While the constructor is running, the variable cat holds no value yet. A half-built object never reaches the variable in main.

4.3.3.4The implicit super() and its errors

The super(); call that the compiler inserts quietly is often useful, but it is also the source of the compile error beginners meet most often. If the superclass has no no-argument constructor, the implicit call has nothing to match:

class Animal {
    private String name;
    Animal(String name) { this.name = name; }
}
class Cat extends Animal {
    Cat(String name) {
        // the compiler inserts super(); here
        System.out.println("Cat");
    }
}
error: constructor Animal in class Animal
  cannot be applied to given types;
  required: String
  found:    no arguments
Cat(String name)super(…) not writtensuper();compiler adds itAnimal() ?none: only Animal(String)fix: super(name); on the first line
Figure 4.3.10: Because super(...) is not written in the constructor of Cat, the compiler inserts super();. Since Animal has only Animal(String), there is no constructor for this call to go to.

The message is confusing at first. The programmer did not call the constructor of Animal, yet the compiler says a call was made with the wrong arguments. What the message says is this: the constructor of Animal expects a String (required: String), but the call has no arguments at all (found: no arguments). The call without arguments is the super(); that the compiler inserted, as seen in Figure 4.3.10.

The same error appears when no constructor is written in the subclass at all:

class Animal {
    private String name;
    Animal(String name) { this.name = name; }
}
class Cat extends Animal { }
Main.java:5: error: constructor Animal in class Animal cannot be applied to given types;
class Cat extends Animal { }
^
  required: String
  found:    no arguments

For a class with no constructor written at all, the compiler adds a no-argument default constructor. The body of this constructor is just super();. So the constructor added for Cat also looks for the no-argument Animal() and cannot find it. The default constructor is added only if the class has no constructor at all. The moment Animal(String) is written in Animal, its no-argument constructor is gone.

The second kind of error is putting super(...) in the wrong place:

Cat(String name) {
    System.out.println("Cat");
    super(name);
}
error: call to super must be first
  statement in constructor

In Java 21, super(...) must be the first statement of the constructor. Not even a println can be written before it. The fix is the same for both errors: on the first line of the subclass constructor, call a suitable superclass constructor explicitly, that is, write super(name);. Another fix is to add a no-argument constructor to the superclass. But that route means letting Animal create a nameless animal, which is usually not wanted.

Common mistake

A programmer who sees the message constructor Animal in class Animal cannot be applied to given types usually looks at the new line that creates the Cat and searches for the error there. The error is in the constructor of class Cat: the parameterized constructor of the superclass was not called. The line number in the message points to this; the line is the constructor declaration of Cat.

The change that came with Java 25 removes this second error. In Java 25, System.out.println("Cat") may be written before super(name); this statement does not touch the object under construction. But even in such statements this cannot be used, methods of the object cannot be called and its fields cannot be read. The core of the rule does not change: the object is not used before its superclass part is built. The first error is fixed by no version; the parameterized constructor of the superclass must still be called explicitly.

4.3.3.5Code trace: this(...) and super(...)

A constructor can call another constructor of the same class with this(...). This is also a form of constructor chaining, and it gathers repeated initialization code in one constructor. Like super(...), this(...) must be the first statement. So a constructor starts with either this(...) or super(...), not both. In the code below, both classes have two constructors:

class Employee {
    private String name;  private double salary;
    Employee(String name) {
        this(name, 20000.0);
        System.out.println("Employee(String)");
    }
    Employee(String name, double salary) {
        this.name = name;  this.salary = salary;
        System.out.println("Employee(String, double)");
    }
    double getSalary() { return salary; }
}
class Manager extends Employee {
    private double bonus;
    Manager(String name) {
        this(name, 5000.0);
        System.out.println("Manager(String)");
    }
    Manager(String name, double bonus) {
        super(name);
        this.bonus = bonus;
        System.out.println("Manager(String, double)");
    }
    double income() { return getSalary() + bonus; }
}
Manager y = new Manager("Ayşe");   // main
System.out.println(y.income());
Employee(String, double)
Employee(String)
Manager(String, double)
Manager(String)
25000.0

A single new runs four constructors. The calls go in this order: Manager(String) → Manager(String, double) through this(name, 5000.0) → Employee(String) through super(name) → Employee(String, double) through this(name, 20000.0) → Object() through the implicit super(). The last constructor in the chain is Employee(String, double); since its first line is neither this nor super, the compiler inserts super() there.

Table 4.3.4: Trace of new Manager("Ayşe"). The fields are name, salary and bonus.
StepEventnamesalarybonusOutput
1new; Manager(String) is callednull0.00.0
2this(name, 5000.0)null0.00.0
3super(name): Employee(String)null0.00.0
4this(name, 20000.0), implicit super(): Object() returnsnull0.00.0
5Body of Employee(String, double)"Ayşe"20000.00.0Employee(String, double)
6Rest of the body of Employee(String)"Ayşe"20000.00.0Employee(String)
7Manager(String, double): bonus = 5000.0"Ayşe"20000.05000.0Manager(String, double)
8Manager(String) finishes"Ayşe"20000.05000.0Manager(String)
9y.income() = 20000.0 + 5000.0"Ayşe"20000.05000.025000.0
StackHeapEmployee(name)Manager(name,bonus)Manager(name)main()y?Manager #1namenullsalary0.0bonus0.0Employee part: name, salarysuper(name) → superclass constructor StackHeapEmployee(name,salary)Employee(name)Manager(name,bonus)Manager(name)main()y?Manager #1name"Ayşe"salary20000.0bonus0.0Employee part: name, salaryEmployee part built StackHeapManager(name,bonus)Manager(name)main()y?Manager #1name"Ayşe"salary20000.0bonus5000.0Employee part: name, salaryManager part being built StackHeapmain()yManager #1name"Ayşe"salary20000.0bonus5000.0Employee part: name, salaryincome() = 20000.0 + 5000.0
Figure 4.3.11: Four moments of the this(...) and super(...) trace. (a) super(name): the Manager part waits until the Employee part is done. (b) The first body runs at the top; name and salary get filled. (c) super(name) has completed; now bonus gets filled. (d) The address of the object is assigned to y.

Table 4.3.4 and Figure 4.3.11 show the same rule once more. The calls go from the bottom up and the bodies complete starting from the top. Four constructors ran, but at no moment, however many constructors were on the stack, was more than one object built. The bonus field stays at 0.0 until step seven. A subclass's own field is not filled until the superclass part is completely finished.

The method income() on the last line adds getSalary(), which arrives by inheritance, and its own bonus field. Since salary is private, Manager cannot read it by name; it uses the getter.

The constructor chain has one limit: it cannot form a cycle. If Employee(String) called this(name, 1.0) and that called this(name), the chain would never reach Object. The compiler catches this:

class Employee {
    Employee(String name) { this(name, 1.0); }
    Employee(String name, double m) { this(name); }
}
error: recursive constructor invocation

Writing both this(...) and super(...) in the same constructor is forbidden too. Each wants to be the first statement:

Manager(String name) {
    this(name, 5000.0);
    super(name);
}
error: call to super must be first statement in constructor

Of the constructors in a chain, only the last one calls super(...). The others delegate to it with this(...).

4.3.3.6The order of initialization in inheritance

Constructors are not the only code that runs when an object is built. The initial values in field declarations (int a = value(...)) and static blocks run too. Once inheritance is involved, the order of these pieces matters. The code below makes the order visible. Each piece prints a trace when it runs:

class Parent {
    static { System.out.println("Parent static"); }
    int a = value("Parent field");
    Parent() { System.out.print("Parent(), "); }
    static int value(String s) {
        System.out.print(s + ", ");
        return 1;
    }
}
class Child extends Parent {
    static { System.out.println("Child static"); }
    int b = value("Child field");
    Child() { System.out.println("Child()"); }
}
// in main:
new Child();
new Child();
Parent static
Child static
Parent field, Parent(), Child field, Child()
Parent field, Parent(), Child field, Child()

The output separates two phases: class initialization and object construction.

Class initialization. Before the JVM (Java Virtual Machine) uses a class for the first time, it initializes it. At this point the static blocks of the class and the initial values of its static fields run. Before a subclass is initialized, its superclass is initialized. That is why “Parent static” is printed first and “Child static” after it. Class initialization happens once per program run.

Object construction. For every new, these four steps run in this order:

  1. the field initializers of the superclass (a = value("Parent field")),
  2. the constructor body of the superclass (Parent()),
  3. the field initializers of the subclass (b = value("Child field")),
  4. the constructor body of the subclass (Child()).

The reason is where the compiler puts the field initializers. The compiler places the assignments from field declarations inside every constructor, right after the super(...) call. So Child() is really compiled like this: first super(), then b = value("Child field"), then the body. Parent() likewise: first super(), that is Object(), then a = ..., then the body.

Classes (once)Parentstatic:runningChildstatic:waitingObjects1. Parent static2. Child static3. Parent fields4. Parent()5. Child fields6. Child()Parent loads: superclass first Classes (once)Parentstatic:ran ✓Childstatic:ran ✓ObjectsChild #1a1b0(a: Parent, b: Child)1. Parent static2. Child static3. Parent fields4. Parent()5. Child fields6. Child()Child() → implicit super() → Parent fields Classes (once)Parentstatic:ran ✓Childstatic:ran ✓ObjectsChild #1a1b0(a: Parent, b: Child)1. Parent static2. Child static3. Parent fields4. Parent()5. Child fields6. Child()Parent() body Classes (once)Parentstatic:ran ✓Childstatic:ran ✓ObjectsChild #1a1b1(a: Parent, b: Child)Child #2a1b1(a: Parent, b: Child)1. Parent static2. Child static3. Parent fields4. Parent()5. Child fields6. Child()second object: no static blocks
Figure 4.3.12: Four moments of the initialization order. (a) For the first new Child(), the static block of Parent runs first. (b) The object has been allocated; the field a of Parent got its initial value. (c) While the body of Parent() runs, b is still 0. (d) The second new Child(): the static blocks do not run again.

The third frame of Figure 4.3.12 shows a dangerous consequence of this order. While the body of Parent() runs, the subclass's field b is still 0. The subclass part has not received any initial value yet. This detail matters when the constructor of the superclass calls a method that the subclass overrides:

class Parent {
    Parent() { print(); }
    void print() { System.out.println("Parent.print"); }
}
class Child extends Parent {
    int b = 7;
    String s = "ready";
    @Override void print() {
        System.out.println("Child.print b=" + b + " s=" + s);
    }
}
// in main:
Child a = new Child();
a.print();
Child.print b=0 s=null
Child.print b=7 s=ready

new Child() runs Parent() first. The print() call inside Parent() goes to Child.print(), because the object is a Child. But at that moment the field initializers of Child have not been assigned yet: b is 0 and s is null. Although the source says int b = 7, the method sees 0. The second call, made after the object is built, sees the right values.

Common mistake

Calling an overridable method in the constructor of a superclass. If a subclass overrides this method, the method runs before the subclass's fields have received their initial values. The result is a wrong computation on default values, or a NullPointerException. If the methods called from a constructor are made private, final or static, they cannot be overridden and the problem goes away.

Example 4.3.3

Instance initializer blocks ({ ... }) run in the same place as field initializers, right after super(...). Given these classes:

class A {
    static { System.out.print("As "); }
    { System.out.print("Ab "); }
    A() { System.out.print("A "); }
}
class B extends A {
    static { System.out.print("Bs "); }
    { System.out.print("Bb "); }
    B() { this(0); System.out.print("B "); }
    B(int x) { System.out.print("B" + x + " "); }
}

What does the first new B() in the program print? First the classes are initialized: As Bs. Then B() is called. Its first line is this(0), so it goes to B(int) without entering its own body. On the first line of B(int) there is an implicit super(): the instance block and body of A run, and Ab A is printed. After super() returns, the instance block of B runs: Bb. Then the body of B(int) prints B0, and last the body of B() prints B. Result: As Bs Ab A Bb B0 B.

The instance block runs not in B() but only in the constructor that calls super(...), that is B(int). So Bb is printed once. If new B(7) is called afterwards, the static blocks do not run again: Ab A Bb B7.

4.3.4Overriding

A subclass does not always want to use a behavior it took from the superclass as it is. A dog does not say “This animal speaks.”; it barks. A rectangle is not drawn like a generic shape but as a rectangle. This section explains how a subclass rewrites a method it received by inheritance, the rules this is subject to, and why those rules exist.

4.3.4.1Overriding a method

Definition 4.3.3

Overriding is the subclass giving its own behavior to a method it inherited from the superclass by rewriting that method with the same signature. The signature of a method is its name and parameter list (the number, types and order of the parameters).

Overriding has four basic conditions:

  • The name and parameter list must be the same.
  • The return type must be the same or a subtype of it.
  • Access cannot be narrowed: a public method must stay public in the subclass.
  • final, static and private methods cannot be overridden.
class Shape {
    public void draw() {
        System.out.println("Drawing a shape.");
    }
}
class Rectangle extends Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle.");
    }
}
// in main
new Shape().draw();
new Rectangle().draw();
Drawing a shape.
Drawing a rectangle.

Rectangle rewrites draw() with the same name, the same (empty) parameter list, the same return type and the same access. new Shape().draw() runs the superclass version, new Rectangle().draw() the subclass version. The actual class of the object decides which version runs. Even when the variable's type is Shape, nothing changes: Shape s = new Rectangle(); s.draw(); still prints “Drawing a rectangle.” This behavior is called dynamic binding and is the foundation of polymorphism.

If one of the conditions is broken, the compiler reports an error. Forgetting to write public in the subclass narrows the access to package level:

// in subclass: void draw()
error: draw() in Rectangle cannot override
  draw() in Shape
  attempting to assign weaker access
  privileges; was public

Changing the return type breaks overriding too:

// in subclass: public int draw()
error: draw() in Rectangle cannot override
  draw() in Shape
  return type int is not compatible
  with void

The first line of both messages is the same: draw() in Rectangle cannot override draw() in Shape. The compiler saw two methods with the same signature and counted this as an attempt to override. The second line says which rule was broken. When reading the message, the real information is on this second line.

4.3.4.2Overriding and overloading

Overriding is often confused with another concept with a similar name: overloading. In overloading, several methods with the same name but different parameter lists are written. The difference between the two is summarized in Table 4.3.5.

Table 4.3.5: Comparison of overriding and overloading.
OverridingOverloading
Where?In the subclass, for an inherited methodIn the same class (or a subclass)
NameSameSame
ParametersSameDifferent (number or type)
Return typeSame or a subtypeFree
PurposeChange an inherited behaviorDo the same job with different inputs
When chosenRun time (actual type of the object)Compile time (types of the arguments)

Both can also be present in the same class:

class Rectangle extends Shape {
    @Override
    public void draw() { ... }             // overriding
    public void draw(String color) { ... }  // overloading
}

The first draw() overrides the method in Shape. The second is draw(String color); because its parameter list is different, it is a new method and overloads draw(). In the call d.draw("blue") the compiler looks at the argument list: a String is given, so draw(String) is chosen. The body of this method adds the color to the start of the message:

Drawing a blue rectangle.

The last row of the table states the most important difference. In overloading, the compiler decides which method to call by looking at the compile-time types of the arguments. In overriding, the decision is made while the program runs, by looking at the actual class of the object. Both concepts are a foundation of polymorphism. The first is called compile-time polymorphism and the second run-time polymorphism.

4.3.4.3The @Override annotation

Definition 4.3.4

@Override is an annotation. It declares that the method overrides a method inherited from a superclass. The compiler checks this declaration: if no method with the same signature exists in the superclasses or interfaces, it reports a compile error.

public class Rectangle extends Shape {
    // override the inherited method
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle.");
    }
}

The annotation is not mandatory; overriding works even if it is not written. But writing it is always recommended. It has two benefits. First, someone reading the code sees at once that the method comes from the superclass. Second, and more important, it catches typos at compile time. Suppose the name of the method is misspelled:

    @Override
    public void Draw() { ... }
error: method does not override or implement
  a method from a supertype

Draw starts with a capital letter. Since Java distinguishes upper and lower case, Draw() and draw() are different methods. What would happen without @Override? The compiler would not complain; Draw() would silently become a new method. The program would run, but behave wrongly:

class Rectangle extends Shape {
    public void Draw() {          // no @Override
        System.out.println("Drawing a rectangle.");
    }
}
// in main:
Shape s = new Rectangle();
s.draw();
Drawing a shape.

For the call s.draw(), Rectangle has no overridden draw(); the search climbs to Shape and the generic version runs. A bug of this kind is noticed only when the program is tried out, perhaps much later. With @Override written, it would have been caught at compile time. The same happens when a parameter type is written wrongly, for example equals(Point) instead of equals(Object).

4.3.4.4The rules of overriding

The rules of overriding can be memorized one by one, but they all derive from a single reason. Table 4.3.6 gives the rules together with the messages javac gives when they are broken. The messages were obtained with JDK 21.

Table 4.3.6: The rules of overriding and the javac messages produced when a rule is broken.
PropertyAllowed in the subclass methodjavac if the rule is broken
Name and parametersExactly the sameNo error: it becomes a new method (overloading)
Return typeThe same or a subtype (covariant)return type String t not compatible with Animal
AccessThe same or wider: protected → publicattempting to assign weaker access privileges
Checked exceptionThe same, a more specific one, or noneoverridden method does not throw Exception
staticAn instance method cannot be static; a static method cannot be an instance methodoverriding method t static / overridden method t static
final methodCannot be overriddenoverridden method t final
private methodInvisible; a method with the same name is an unrelated new methodNo error (error if @Override is present)

The common reason is this: a subclass object must be usable wherever a superclass object is expected. Code that works with a variable of type Shape does not know whether the object the variable refers to is really a Rectangle or a Circle. This code relies only on the promise Shape makes. The promise of the superclass has three parts: what the method returns, to whom it is open, and which exceptions it may throw. The subclass may keep this promise or widen it, but cannot narrow it.

With this reason the rules explain themselves one by one. If the superclass's method is public, it can be called from anywhere. Had the subclass lowered it to package access, a call from another package through a Shape variable would be forbidden when it reached a Rectangle object. Widening access creates no problem. Making a protected method public breaks none of the old callers.

Exceptions follow the same logic. If the superclass method f() declares no checked exception, the code that calls it has not written try-catch. If the subclass version says throws Exception, this code would be caught unprepared. The compiler prevents this:

class Parent { void f() { } }
class Child extends Parent {
    @Override void f() throws Exception { }
}
error: f() in Child cannot override f() in Parent
  overridden method does not throw Exception

The reverse is allowed. If the superclass declares throws Exception, the subclass may declare a more specific exception (throws IOException) or none at all. The caller is already ready to catch Exception; a more specific exception falls within it. RuntimeException and its subclasses are unchecked exceptions; this rule does not apply to them.

Example 4.3.4

Given class U { protected void a() { } public void b() { } }. Inside class V extends U we write @Override public void a() { } and @Override void b() { }. Which one compiles?

a() is protected in the superclass; making it public in the subclass widens the access, so it compiles. b() is public in the superclass; writing it without a modifier lowers the access to package level. javac gives the messages b() in V cannot override b() in U and attempting to assign weaker access privileges; was public. The order of access from narrow to wide is: private, package, protected, public.

4.3.4.5Covariant return type

The return type rule looks strict on first reading, but it has some flexibility. An overriding method may return a subtype of the return type in the superclass:

class Animal {
    Animal reproduce() { return new Animal(); }
    public String toString() { return "Animal"; }
}
class Cat extends Animal {
    @Override
    Cat reproduce() { return new Cat(); }  // subtype
    void meow() { System.out.println("meow"); }
    public String toString() { return "Cat"; }
}
// in main:
Cat k = new Cat();
k.reproduce().meow();   // no cast needed
Animal h = k;
System.out.println(h.reproduce());
meow
Cat
Definition 4.3.5

A covariant return type means that an overriding method returns a subtype of the return type declared in the superclass.

Animal.reproduce() returns an Animal. Cat.reproduce() returns a Cat; since Cat is a subtype of Animal, this is a valid override. The benefit shows at the first call. A caller that uses a Cat reference receives the result directly as a Cat. k.reproduce().meow() can be written, with no (Cat) cast. If the return type had stayed Animal, the call to meow() would not compile, because Animal has no such method.

For a caller that uses an Animal reference, the promise is not broken. The compile-time type of h.reproduce() is Animal, and what comes back really is an animal, because a Cat is an Animal too. Since the object is a Cat, the call goes to Cat.reproduce(); println calls the toString() of the new cat and prints “Cat”.

Covariance applies only to reference types. A method that returns int cannot be overridden to return long; there is no subtype relation between primitive types. An unrelated reference type is not allowed either:

error: reproduce() in Cat cannot override
  reproduce() in Animal
  return type String is not compatible with Animal

String is not a subtype of Animal. Code that calls reproduce() through an Animal variable expects an animal and would get a string. The compiler does not allow this.

4.3.4.6private and static methods

A private method is invisible to the subclass. A method written in the subclass with the same name does not override it; it is a new method, unrelated to it. This sometimes produces unexpected results:

class Parent {
    private void greet() { System.out.println("Parent.greet"); }
    void call() { greet(); }
}
class Child extends Parent {
    void greet() { System.out.println("Child.greet"); } // new
}
// in main:
Child a = new Child();
a.call();
a.greet();
Parent.greet
Child.greet

a.greet() calls the method of Child, as expected. The surprise is the result of a.call(). call() is written in Parent, and Child inherits it. The call to greet() inside it is bound at compile time to Parent's own private method. Since private methods cannot be overridden, the compiler does not leave this call to run time. Even though the object is a Child, “Parent.greet” is printed.

If greet() in Parent were not private, the situation would reverse:

class Parent {
    void greet() { System.out.println("Parent.greet"); }
    void call() { greet(); }
}
class Child extends Parent {
    @Override void greet() { System.out.println("Child.greet"); }
}
// in main:
new Child().call();
Child.greet

Here Child.greet() really does override. The call in call() is chosen by the actual class of the object, and the version in Child runs. The only difference between the two programs is the word private, but the behavior changes completely.

If a programmer thinks Child.greet() overrides, the @Override habit exposes the misunderstanding. If @Override is added to Child.greet() in the private example, the compiler gives the message method does not override or implement a method from a supertype. The annotation says “I think I am overriding, please check”; the compiler reports the result of the check.

The same happens with static methods. A static method with the same signature in the subclass does not override the one in the superclass; it only hides it. Which one runs is decided not by the object but by the compile-time type of the variable:

class Parent {
    static void f() { System.out.println("Parent.f"); }
    void g() { System.out.println("Parent.g"); }
}
class Child extends Parent {
    static void f() { System.out.println("Child.f"); }
    @Override void g() { System.out.println("Child.g"); }
}
// in main:
Parent u = new Child();
u.f();
u.g();
Parent.f
Child.g

u refers to a Child object, but its type is Parent. The static method f() belongs to the class. The compiler reads u.f() as Parent.f() and never looks at the object. The instance method g(), on the other hand, is overridden; the actual class of the object makes the choice. That is why calling a static method through an object variable is misleading. The right way to write it is Parent.f() or Child.f(). Writing an instance method and a static method with the same signature, in either order, is a compile error:

error: f() in Child cannot override f() in Parent
  overriding method is static
error: f() in Child cannot override f() in Parent
  overridden method is static

4.3.4.7Example: a product hierarchy

The power of overriding shows in calls the superclass makes from inside itself. In a store program, let the selling price of products be computed by adding VAT (value-added tax). Food products have a different VAT rate; some products carry a discount.

class Product {
    private String name;
    private double price;
    Product(String name, double price) {
        this.name = name; this.price = price;
    }
    double taxRate() { return 0.20; }
    double salePrice() { return price * (1 + taxRate()); }
    @Override public String toString() {
        double f = Math.round(salePrice() * 100) / 100.0;
        return name + ": " + f + " TL";
    }
}
class Food extends Product {
    Food(String name, double price) { super(name, price); }
    @Override double taxRate() { return 0.01; }
}
class SaleProduct extends Product {
    private double discount;
    SaleProduct(String name, double price, double discount) {
        super(name, price);
        this.discount = discount;
    }
    @Override double salePrice() {
        return super.salePrice() * (1 - discount);
    }
    @Override public String toString() {
        return super.toString()
            + " (" + (int) (discount * 100) + " % off)";
    }
}

Class Product splits the price computation into two steps. taxRate() gives the rate, and salePrice() computes with that rate. toString() rounds the selling price to two decimals and prints it with the name. For rounding, the pattern Math.round(x * 100) / 100.0 is used. This pattern cleans up the long tails floating-point arithmetic can produce; for example, the result of 0.1 + 0.2 is 0.30000000000000004.

The two subclasses follow two different paths. Food changes only taxRate(). SaleProduct overrides salePrice() but does not replace the computation of the superclass; it extends it. It applies the discount to the result of super.salePrice(). It extends toString() too, and appends the discount rate at the end.

Product[] cart = {new Product("Pen", 50),
    new Food("Bread", 10),
    new SaleProduct("Headphones", 1000, 0.25)};
for (Product u : cart) System.out.println(u);
Pen: 60.0 TL
Bread: 10.1 TL
Headphones: 900.0 TL (25% off)
Table 4.3.7: Which method runs for each product in the cart, and the computation.
ProducttaxRate()salePrice()ComputationResult
Pen (Product)Product: 0.20Product50 × 1,2060.0
Bread (Food)Food: 0.01Product10 × 1,0110.1
Headphones (SaleProduct)Product: 0.20SaleProduct → super1000 × 1,20 × 0,75900.0

The second row of Table 4.3.7 is the most instructive part of the example. salePrice() and toString() are not written in Food. Both come from Product. But the call to taxRate() inside salePrice() means this.taxRate(), and this is a Food. The call is chosen by the class of the object; the 1% rate is used. The code of the superclass ends up calling a method written by a subclass. When the superclass was written, Food perhaps did not exist yet.

In the third row the chain has two levels. toString() is first the one in SaleProduct, and it calls the one in Product with super.toString(). Product.toString() calls salePrice(); since the object is a SaleProduct, SaleProduct.salePrice() runs. It has Product do its computation with super.salePrice(): 1000 × 1.20 = 1200. Then it applies the discount: 1200 × 0.75 = 900. The discount rate is converted to an integer with (int) (discount * 100) and “25%” is printed.

Example 4.3.5

Consider three products priced at 200 TL: a plain Product, a Food and a SaleProduct with a 10% discount. What are their selling prices?

Product: 200 × 1.20 = 240.0. Food: taxRate() returns 0.01, so 200 × 1.01 = 202.0. SaleProduct: first super.salePrice() = 240, then 240 × 0.90 = 216.0. The discount is applied to the price with VAT. Applying it to the price without VAT would not change the result, because the order of multiplication does not affect the product: 200 × 0.90 × 1.20 is also 216.

This design shows that the superclass can be extended with new kinds of products without being closed to change. To add a product with a luxury consumption tax, a new subclass overrides taxRate() or salePrice(). There is no need to touch Product or the loop that walks through the cart.

4.3.5Access and restriction

Inheritance opens the inside of the superclass to subclasses to some degree. How much it opens is part of the design. This section first describes protected, an access level made for subclasses. It then covers final, which closes inheritance completely, and narrowing the view of an object through its superclass type.

4.3.5.1The protected access level

Java has four access levels. public members are reachable from everywhere. private members are reachable only from inside their class. Members with no modifier have package access; all classes in the same package see them. protected is a level between package access and public.

Table 4.3.8: Scope of the access modifiers (✓ accessible, ✗ not accessible).
ModifierSame classSame packageSubclass (other package)Everywhere
private✓✗✗✗
(no modifier: package)✓✓✗✗
protected✓✓✓✗
public✓✓✓✓
Definition 4.3.6

A protected member can be accessed by the class itself, by all classes in the same package, and by subclasses in other packages.

Table 4.3.8 shows a wider scope in each row than in the one before. The word protected sounds restrictive, but as the table shows, it is more open than package access. This is often confused. protected adds one more permission on top of package access: it opens the member to subclasses in other packages.

A subclass can reach the private fields of a class only through the public or protected methods it inherits from the superclass. Good practice is this: the fields stay private, and the operations subclasses need are opened as protected methods. Making a field protected looks easy, but the responsibility for checking the field's value is now spread over all subclasses. A subclass can set health to −50, and Animal has no chance to prevent it.

4.3.5.2protected: a code example

The two classes below are in different packages. Animal is in package animals, Cat in package indoor.

package animals;

public class Animal {
    protected String name;  // subclasses
    private double health;  // Animal only

    public Animal(String name) {
        this.name = name;
        health = 100.0;
    }
    public double getHealth() { return health; }
    protected void heal(double amount) {
        health += amount;
    }
}
package indoor;     // another package
import animals.Animal;

public class Cat extends Animal {
    public Cat(String name) { super(name); }
    public void sleep() {
        // protected field: allowed
        System.out.println(name + " is sleeping.");
        // health += 5;  // private: error
        heal(5);   // protected method
        System.out.println("Health: "
                           + getHealth());
    }
}

The two fields of Animal show two different design choices. name is protected; subclasses can read it directly. health is private. It can be reached in only two ways: the public getHealth() reads it, and heal(double), open only to subclasses, changes it.

The sleep() method of Cat uses both ways. It writes name directly; although Cat is in another package, it is a subclass of Animal. It raises health with heal(5) and reads it with getHealth(). new Cat("Mavi").sleep(); prints:

Mavi is sleeping.
Health: 105.0

If the health += 5; in the comment is uncommented, compilation stops:

error: health has private access in Animal

The benefit of this design is concrete. The owner of Animal may later want health never to exceed 100. They write this rule only in heal; all subclasses comply automatically. If the field were protected, the code of every subclass would have to be checked one by one.

A class that is not a subclass cannot reach a protected member from another package:

package other;
import animals.Animal;
public class Keeper {             // not a subclass
    String name(Animal h) { return h.name; }
}
other/Keeper.java:4: error: name has protected access in Animal

Keeper is neither in package animals nor a subclass of Animal. None of the four columns of the table allows it. If Keeper were moved to package animals, it would compile: classes in the same package can reach protected members.

4.3.5.3The fine print of protected access

One rule of protected does not fit in the table. A subclass in another package can reach a protected member only through a reference of its own type (or its own subtypes):

package animals;
public class Animal {
    protected String name;
    public Animal(String name) {
        this.name = name;
    }
}
package indoor;
import animals.Animal;
public class Cat extends Animal {
    public Cat(String name) { super(name); }
    void compare(Cat k, Animal h) {
        System.out.println(name);    // its own field
        System.out.println(k.name);  // through Cat
        System.out.println(h.name);  // through Animal
    }
}
indoor/Cat.java:8: error: name has protected access in Animal
        System.out.println(h.name);

The three lines in the method compare use three different references. name alone means this.name; this is a Cat, and access is allowed. In k.name, the type of k is Cat; that is allowed too. In h.name, the type of h is Animal, and compilation stops.

The reason for the rule lies in what h may refer to. h could be any Animal, for example a Dog. The permission protected gives is “a subclass may touch the part it inherited”. A cat touching the internal data of a dog is outside this permission. That is why the compiler does not allow a reference of type Animal. For the same reason a parameter of type Dog does not work either: inside Cat, k.name with k a Dog again produces the message name has protected access in Animal.

Classes in the same package have no such restriction. There protected includes package access. A class Vet in package animals can read the name of any Animal and call heal, even though it is not a subclass.

4.3.5.4Limiting inheritance with final

The final keyword is used to limit inheritance. If a method is declared final, no subclass can override it. If a class is declared final, no subclass can be derived from it.

class Animal {
    public final void breathe() { ... }
}
class Cat extends Animal {
    public void breathe() { ... }
}
error: breathe() in Cat cannot override
  breathe() in Animal
  overridden method is final
final class Fixed { ... }
class Test extends Fixed { }
error: cannot inherit from final Fixed
class Testfinal class Fixedextends ✗Cat.breathe()final breathe()overriding ✗
Figure 4.3.13: No subclass can be derived from a final class; a final method cannot be overridden in a subclass.

The Java library has many final classes: String, Math and Integer are among them. Writing class MyString extends String { } gives the error cannot inherit from final String. The reason is security and consistency. String objects must be immutable. When a method receives a String, it trusts that the text will not change later. File names, network addresses and HashMap keys, for example, rely on this trust. If String had a mutable subclass, this promise would be broken. final closes that door.

A final method is used for a similar reason. If the breathe() method of Animal is critical for the correctness of the health computation, no subclass should change it. Making the methods called from a constructor final also prevents an override that reads fields of the subclass that have not been initialized yet.

For variables, final carries another meaning: the variable is assigned once and becomes a constant. The same word carries three meanings in three places. What they share is “from now on, no change”: the value of the variable, the body of the method, the place of the class in the hierarchy.

4.3.5.5Narrowing the view of an object

A subclass object can be assigned to a variable of the superclass type. This assignment is called upcasting. The assignment happens by itself, no cast operator is needed, because every Tire is a Part.

Part p = new Tire("Petlas", "XYZ-123", "225/45R17", true);
System.out.println(p.serialNumber());   // allowed → XYZ-123
// p.isWinter()                         // not allowed
Part pTire objectPart portion · visible through pbrand = "Petlas"serialNo = "XYZ-123"serialNumber()Tire portion · not visible through psize = "225/45R17"winter = trueisWinter()
Figure 4.3.14: The reference p of type Part refers to a Tire object. Through p only the Part portion of the object is visible; size, winter and isWinter() stay hidden.

Figure 4.3.14 shows an important distinction. The object itself has not changed; it is still a Tire with all its fields. What has changed is only the width of the window through which it is seen. The compiler decides which methods can be called by looking at the type of the variable. The type of p is Part; Part has serialNumber() and does not have isWinter():

error: cannot find symbol
  symbol:   method isWinter()
  location: variable p of type Part

This restriction is a design tool. If a method takes a Part as a parameter, it works with every kind of part and can use only operations specific to parts. That way only the needed face of the object is opened to the outside. A method that counts stock does not have to know whether a tire is a winter tire.

To reach a method specific to Tire, downcasting is used. A downcast is written explicitly and checked at run time. That is why the type is first checked with instanceof:

Part p = new Tire("Petlas", "XYZ-123", "225/45R17", true);
if (p instanceof Tire) {
    Tire l = (Tire) p;          // safe
    System.out.println(l.isWinter());
}
Part q = new Part("Bosch", "AB-9");
Tire l2 = (Tire) q;             // q is not a Tire
true
Exception in thread "main" java.lang.ClassCastException: class Part cannot be cast to class Tire

Because p instanceof Tire is true, (Tire) p is safe and true is printed. q is a plain Part. The compiler accepts (Tire) q, because a Part variable may be referring to a Tire. At run time the JVM looks at the object, sees that it is not a Tire, and throws ClassCastException. A downcast does not produce a new object. It lets you look at the same object through a wider window; if the object does not fit that window, an exception occurs.

Common mistake

An unchecked downcast: writing (Tire) p causes ClassCastException if p is not a Tire. Before the cast, the check if (p instanceof Tire) is made. Since Java 16 the two can be written in one step: if (p instanceof Tire l) { … l.isWinter() … }. Here l holds the cast reference if the check is true.

4.3.6Relationships between classes

Inheritance is not the only way to relate two classes. A class can also hold an object of another class as a field. This section compares the two relationships, explains why Java does not allow multiple inheritance, and shows with code traces two problems inheritance causes when it is misused.

4.3.6.1The is-a and has-a relationships

Definition 4.3.7

The is-a (“is a kind of”) relationship is inheritance: a class is derived from another class and becomes a kind of it. A subclass object can also be used as an object of the superclass.

The has-a (“owns”) relationship is composition: a class contains a field of another class's type. The object holds references to other objects inside it.

The easiest way to tell the two relationships apart is to form a sentence. “A car is a vehicle” is a correct sentence; Car extends Vehicle is written. “A car is an engine” is wrong. The correct sentence is “a car has an engine”; the engine becomes a field of the car. Real classes often carry both relationships together:

// Is-a relationship (inheritance)
public class Car extends Vehicle {
    // Has-a relationship (composition)
    private Engine engine;

    public Car(int horsepower) {
        engine = new Engine(horsepower);
    }
    public void drive() {
        engine.start();   // delegate to Engine
        accelerate(50);         // inherited from Vehicle
        System.out.println("Speed: " + speed
                           + " km/h");
    }
}
// Engine: horsepower field and start():
//   "Engine started: " + horsepower + " HP"
Vehicle# speed : int+ accelerate(int) : voidCar- engine : Engine+ drive() : voidEngine- horsepower : int+ start() : voidis-ahas-a
Figure 4.3.15: Car derives from Vehicle (is-a). Car contains an Engine object (has-a). In UML, composition is drawn with a filled diamond on the side of the containing class.

Class Vehicle has a speed field and an accelerate(int) method; speed is protected so that subclasses can reach it. Class Engine holds the horsepower, and its start() method prints “Engine started: … HP”. Car creates its own engine in its constructor. Its drive() method uses both relationships together: it delegates the job of starting the engine to the Engine object, and accelerates with the method it inherited from Vehicle. new Car(110).drive(); prints:

Engine started: 110 HP
Speed: 50 km/h

4.3.6.2Code trace: car and engine

The difference between the two relationships in memory can be seen with a trace. The trace in the slides uses a shortened version of the same classes:

class Engine {
    private int hp;
    Engine(int hp) { this.hp = hp; }
    void start() {
        System.out.println("Engine: " + hp + " HP");
    }
}
class Car extends Vehicle {        // is-a
    private Engine engine;           // has-a
    Car(int hp) { engine = new Engine(hp); }
    void drive() {
        engine.start();  accelerate(50);
        System.out.println("Speed: " + speed);
    }
}
new Car(90).drive();   // main
Engine: 90 HP
Speed: 50
StackHeapCar()thishp90main()Car #1speed (Vehicle)0enginenullVehicle part (speed) + Car part (engine) StackHeapCar()thishp90main()Car #1speed (Vehicle)0engineEngine #2hp90 StackHeapstart()thisdrive()thismain()Car #1speed (Vehicle)0engineEngine #2hp90engine.start() → the Engine object does the work StackHeapdrive()thismain()Car #1speed (Vehicle)50engineEngine #2hp90accelerate(50): method that arrives by inheritance from Vehicle
Figure 4.3.16: Four moments of the is-a and has-a trace. (a) new Car(90) creates a single object; the speed that comes from Vehicle is inside this object. (b) The constructor creates a second object, an Engine; the engine field refers to it. (c) engine.start(): the work is delegated to Engine by following the reference. (d) accelerate(50) sets the speed field of the same Car object to 50.

Figure 4.3.16 clearly separates what the two relationships look like in memory. Inheritance gives a single object. The speed field is not in a separate Vehicle object but in the Car object itself. Composition gives two separate objects. The engine field in the Car object is a reference to another object on the heap. A car is not an engine; it has one. The link is a reference.

The flow of the calls differs too. In the call engine.start(), Car does not do the work itself; it follows the reference and delegates to the Engine object. A start() frame is added to the stack, and the this in that frame refers to the Engine object. In the call accelerate(50), this does not change; the method is written in Vehicle but works on the same Car object.

4.3.6.3Multiple inheritance

In Java, a class can derive from only one class; multiple inheritance of classes is not directly supported:

class D extends B, C { }   // invalid
error: '{' expected
class D extends B, C { }
                 ^

The message looks a little odd. The compiler does not say “multiple inheritance is forbidden”; it reports a syntax error. After extends it expects a single class name, and right after the name it looks for the { of the class body. It stops when it sees the comma.

A+ print()B+ print()C+ print()Dprint() → ?
Figure 4.3.17: The diamond problem. If D derived from both B and C, and both overrode the print() method of A differently, it would be unclear which one D gets.

The reason for the ban is the diamond problem. Figure 4.3.17 shows the situation: B and C derive from A, and both override print() differently. If D could derive from both, which version would d.print() run? Because the diagram looks like a diamond, the problem has this name. The problem has a second face: should the fields of A be present once or twice in a D object? Languages that allow multiple inheritance, such as C++, answer these questions with complicated rules. The designers of Java chose not to take multiple inheritance of classes at all.

If the abilities of several classes are needed, there are two ways. The first is composition: the class holds as fields the objects whose abilities it wants to use. The second is interfaces. A class can extend a single class while implementing many interfaces:

interface Chargeable { void charge(); }
class ElectricCar extends Car
                      implements Chargeable {
    @Override
    public void charge() {
        System.out.println("Charging.");
    }
}

ElectricCar is both a Car and something that can be charged. The interface makes just one promise: there will be a method called charge(). The class writes the body. Because classic interfaces have no fields, the field face of the diamond problem does not arise.

4.3.6.4Design principles: inheritance or composition?

Four principles guide design with inheritance.

  • The is-a test. If the sentence “Is every X a Y?” is not true, inheritance is not used. A car is not an engine, it has one; the right relationship is composition.
  • Each class manages its own data. The fields of the superclass are given values with super(...) and the methods of the superclass; the fields are kept private.
  • Override the general methods. toString and equals, and with it hashCode, should be overridden in every meaningful class.
  • Shared concepts go to an abstract class. If “Animal” alone should not be an object, that is, if nobody should create a vague “animal”, the common concept of the subclasses is represented by an abstract class.

The choice between inheritance and composition is an application of the first principle. Table 4.3.9 compares the two ways on a few criteria.

Table 4.3.9: Comparison of inheritance and composition.
Inheritance (extends)Composition (object as a field)
Relationshipis-a: “every X is a Y”has-a: “X has a Y”
CouplingTight: the subclass depends on the internals of the superclass tooLoose: depends only on the public methods of the inner object
ReuseAutomatic: all public methods come along (even unwanted ones)Selective: only the methods that should be forwarded are written
ChangeThe superclass is fixed at compile timeThe field can be replaced with another object at run time
Use in place of the supertypeDirect: Animal h = new Cat()If a common interface is implemented

Inheritance is appropriate when the is-a relationship is really true and the superclass was designed and documented to be extended. Cat and Animal fit this case. Composition is appropriate when the goal is only to use the code of another class. A stack class is an example. MyStack can use an ArrayList to hold its elements. But a stack is not a list. If MyStack extends ArrayList is written, the stack also receives all the public methods of the list. Someone can insert an element into the middle of the stack with add(0, x). This breaks the stack's rule “add and remove only at the top”. The right way is to keep the list in a private field and expose only push and pop.

The Change row states an important difference too. Because the engine of a Car is a field, it can be replaced while the program runs. The gasoline engine is removed and an electric engine installed; if both implement a common Engine interface, the code of Car does not change. With inheritance, the superclass of Car is written in the source code and does not change once compiled.

4.3.6.5Code trace: the fragile base class

The tight coupling of inheritance sometimes causes unexpected bugs. The example below has a list class. The goal is to write a subclass that counts the elements added to it.

class MyList {
    private String[] items = new String[10];
    private int size;
    void add(String s) { items[size++] = s; }
    void addAll(String[] arr) {
        for (String s : arr) add(s);
    }
    int size() { return size; }
}
class CountingList extends MyList {
    int addCount = 0;
    @Override void add(String s) {
        addCount++;
        super.add(s);
    }
    @Override void addAll(String[] arr) {
        addCount += arr.length;
        super.addAll(arr);
    }
}
CountingList l = new CountingList();   // main
l.addAll(new String[] {"a", "b", "c"});
System.out.println(l.addCount + " " + l.size());
6 3

Three elements were added and the list really holds three, but the counter says 6. Both methods of CountingList look right on their own. add increases the counter by one and leaves the work to the superclass. addAll adds the length of the array to the counter and leaves the work to the superclass. Table 4.3.10 shows the source of the bug step by step.

Table 4.3.10: Trace of l.addAll({"a", "b", "c"}).
StepMethod runningEventaddCountsize
1CountingList.addAllThe object is a CountingList; the version in the subclass is called.00
2CountingList.addAlladdCount += arr.length30
3MyList.addAllsuper.addAll(arr); the loop calls add("a"), that is this.add("a").30
4CountingList.addthis is a CountingList: the overridden add runs and the counter goes up.40
5MyList.addsuper.add(s) writes the element into the array.41
6(loop)Steps 3–5 repeat for "b" and "c".63
7mainprintln: wrong result63
StackHeapCountingList.addAllmain()lCountingList #1addCount3size0items[ ]size, items: MyList part (private)arr.length = 3 added StackHeapCountingList.addMyList.addAllCountingList.addAllmain()lCountingList #1addCount4size0items[ ]size, items: MyList part (private)this is a CountingList → overridden add StackHeapMyList.addCountingList.addMyList.addAllCountingList.addAllmain()lCountingList #1addCount4size1items[a]size, items: MyList part (private)super.add: the element is really added StackHeapmain()lCountingList #1addCount6size3items[a, b, c]size, items: MyList part (private)three elements, counter 6: fragile base class
Figure 4.3.18: Four moments of the fragile base class trace. (a) addAll of the subclass adds 3 to the counter. (b) The add(s) in the superclass's loop returns to the subclass because the object is a CountingList; the same element is counted a second time. (c) super.add writes the element: size = 1. (d) The result is 6 3.

The bug is born in the third step. MyList.addAll does its work by calling add(s) for each element. This is an implementation detail of MyList; it may not be written in the class's documentation. The add(s) in the code of MyList is really this.add(s), and this is a CountingList. The call goes to the overridden version. Each element is counted once in addAll and once again in add.

Definition 4.3.8

The fragile base class problem is that the correctness of a subclass depends on the internals of its superclass. Even a change in the superclass that does not alter its externally visible behavior can break the subclass.

Here is the fragility side of the problem. The programmer of CountingList may notice the bug and delete the override of addAll. The counter is then correct, because each element is counted only in add. But this fix depends on the code MyList has today. If a new version of MyList writes addAll to copy the array directly for speed, add is never called and the counter stays at 0. In both cases the behavior MyList offers its users is the same, but CountingList breaks.

Example 4.3.6

On a new CountingList, first add("x") and then addAll(new String[] {"y", "z"}) are called. What are addCount and size()?

add("x") runs the subclass's add directly: counter 1, size 1. addAll first adds 2 to the counter: counter 3. Then the loop of the superclass calls add twice and each goes back to the subclass: counter 5, size 3. The result is 5 3. Had only add been used, the result would have been right; the bug comes from overriding addAll and add together.

4.3.6.6The composition fix: forwarding

The clean fix for the fragile base class problem is to give up inheritance and move to composition:

class CountingList2 {
    private final MyList list = new MyList(); // has-a
    private int addCount = 0;
    void add(String s) {
        addCount++;
        list.add(s);            // forwards
    }
    void addAll(String[] arr) {
        addCount += arr.length;
        list.addAll(arr);  // forwards
    }
    int getAddCount() { return addCount; }
    int size() { return list.size(); }
}
CountingList2 l2 = new CountingList2();
l2.addAll(new String[] {"a", "b", "c"});
System.out.println(l2.getAddCount()
    + " " + l2.size());
3 3
Definition 4.3.9

Forwarding is passing a call that arrives at the composing class on to a method of the inner object. Each method of the outer class first does its own work, then forwards the call to the inner object.

The new class does not derive from MyList; it holds a MyList inside. The add calls inside list.addAll(...) run on a plain MyList object. The this of that object is a MyList; the call does not come back to CountingList2. The counter is right: 3. Even if the internal detail of MyList changes, the result does not. CountingList2 depends only on the public methods of MyList.

This solution has a price. CountingList2 is not a MyList; it cannot be given where a MyList is expected. If needed, MyList and CountingList2 implement a common interface and the code is written against that interface type. The forwarding approach is common in the Java library too. For example, Collections.unmodifiableList(...) returns an object that wraps a list and forwards read calls to it.

4.3.6.7The substitution principle

The is-a test can be misleading when it is applied in everyday language. In mathematics every square is a rectangle. Based on this sentence, writing Square extends Rectangle seems natural:

class Rectangle {
    protected int width, height;
    void setWidth(int width) { this.width = width; }
    void setHeight(int height) { this.height = height; }
    int area() { return width * height; }
}
class Square extends Rectangle {
    @Override void setWidth(int k) { width = k; height = k; }
    @Override void setHeight(int k) { width = k; height = k; }
}
static void widen(Rectangle d) {
    d.setWidth(5);
    d.setHeight(4);
    System.out.println("Expected 20, got "
        + d.area());
}
// in main:
widen(new Rectangle());
widen(new Square());
Expected 20, got 20
Expected 20, got 16
Definition 4.3.10

The Liskov substitution principle (LSP): code written against a superclass type must also work correctly with an object of a subclass. It is not enough for the code to compile; the behavior must stay correct as well.

The method widen sets the width of a rectangle to 5 and its height to 4 and expects the area to be 20. With a plain Rectangle the expectation holds. With a Square, setWidth(5) sets both sides to 5, and then setHeight(4) sets both sides to 4. The area comes out as 16. The code compiled, no exception occurred, but the result is wrong.

Where is the bug? widen is not faulty. Class Rectangle makes the promise “width and height change independently of each other”: setWidth does not touch the height. widen relied on this promise. Square cannot keep it, because the two sides of a square cannot be independent. The fault lies with the subclass that broke the promise. The mathematical relationship is true, but the relationship between the classes is wrong.

There are two common solutions to this problem. The first is not to derive Square from Rectangle; both derive from a common Shape and each writes its own area(). The second is to make the classes immutable. Width and height are given only in the constructor, and there are no setWidth and setHeight at all. Then there is no promise like “changing the width leaves the height alone”, and a square can really behave like a rectangle.

The lesson is this: the is-a test is applied not to the real world but to the behavior of the class. The right question is not “is a square a rectangle?” but “can Square answer every method of Rectangle the way a Rectangle does?”

Example 4.3.7

After the lines Rectangle d = new Square(); d.setWidth(3); d.setHeight(7);, what is d.area()?

The type of the variable is Rectangle, and the object is a Square. The calls go to the overridden versions. setWidth(3): width = height = 3. setHeight(7): width = height = 7. The area is 7 × 7 = 49. The last call determines both sides. With a plain rectangle the result would be 3 × 7 = 21.

4.3.7The Object class

Every class in Java derives from Object, whether or not it is written. This section describes the methods Object gives every object and how to override the three most important of them, toString, equals and hashCode, correctly.

4.3.7.1The ancestor of every class

Every class derives from java.lang.Object. If extends is not written, this happens implicitly:

class Point { }
// what the compiler sees:
class Point extends Object { }

That is why some methods are ready on every object. Table 4.3.11 gives the four most used. The default versions of these methods are general-purpose and often useless. In meaningful classes the first three are overridden.

Table 4.3.11: The most commonly used methods of the Object class.
MethodDefault behavior
String toString()The class name + @ + the hexadecimal form of the hashCode value
boolean equals(Object o)Compares references: this == o
int hashCode()An integer specific to the object (usually different for each object)
Class getClass()The runtime class of the object (final; cannot be overridden)

Object has other methods too: wait, notify and notifyAll, used with threads, and clone, used to copy objects. They are not the subject of these notes. A variable of type Object can refer to any object. That is why the parameter of equals is Object: an object must be comparable with any other object.

4.3.7.2The toString method

public String toString() shows an object as text. System.out.println(obj) and concatenation of the form "..." + obj call this method automatically. If it is not overridden, a text containing the class name and the hashCode value of the object is returned:

class Point {
    private int x, y;
    Point(int x, int y) {
        this.x = x; this.y = y;
    }
}
// in main
System.out.println(new Point(3, 4));
Point@28a418fc

The 28a418fc after the @ sign is the hexadecimal form of the hashCode() value. The value may differ on every run or on every JVM. It says nothing about the contents of the object; it is useless even when debugging. Once overridden, the object is printed readably:

class Point {
    private int x, y;
    Point(int x, int y) {
        this.x = x; this.y = y;
    }
    @Override
    public String toString() {
        return "Point[x=" + x + ", y=" + y + "]";
    }
}
// in main
Point n = new Point(3, 4);
System.out.println(n);
System.out.println("Position: " + n);
Point[x=3, y=4]
Position: Point[x=3, y=4]

On the second line, because one side of the + operator is a String, Java converts the other side to text too, and calls toString() for it. The return type of toString() is String and its access is public. Forgetting to write public when overriding gives the access-narrowing error seen in Table 4.3.6.

There is one more detail. If a null reference is printed, toString is not called; “null” is printed:

Point n = null;
System.out.println(n);
System.out.println("Position: " + n);
null
Position: null

println and string concatenation treat null specially. But had n.toString() been called explicitly, a NullPointerException would occur; a method cannot be called on a null reference.

4.3.7.3== or equals?

There are two ways to compare two objects, and they ask different questions. == asks, “do these two references point to the same object?” equals asks, “are these two objects equivalent?” In the Person class below, let equals be overridden to compare name and age:

Person k1 = new Person("Ali", 25);
Person k2 = new Person("Ali", 25);
Person k3 = k1;
System.out.println(k1 == k2);
System.out.println(k1 == k3);
System.out.println(k1.equals(k2));
false
true
true
k1k2k3Person object #1name = "Ali"age = 25Person object #2name = "Ali"age = 25 k1k2k3Person object #1name = "Ali"age = 25Person object #2name = "Ali"age = 25#1 ≠ #2 → false
Figure 4.3.19: Two moments of the == and equals trace. (a) k3 = k1 only copies the address; k1 and k3 point to the same object. (b) k1 == k2: two separate objects, the result is false.

Let us follow the lines in order. The first two new expressions create two separate objects with the same content on the heap; k1 and k2 hold their addresses. k3 = k1 does not create a new object; it only copies the address. Now k1 and k3 point to the same object (Figure 4.3.19). k1 == k2 compares two different addresses and gives false. k1 == k3 compares the same address and gives true. k1.equals(k2) compares the contents: both objects have the name "Ali" and the age 25, so the result is true.

Had equals not been overridden, the last line would give false. The equals of Object is just this == o. For String comparison the rule is the same: write s1.equals(s2), not s1 == s2. new String("Java") == new String("Java") gives false, and equals gives true.

4.3.7.4The equals contract

public boolean equals(Object other) says whether two objects are equivalent. By default it only compares references; if it is not overridden, it behaves like ==. Once overridden, the method compares the state of the two objects, that is, their fields, and returns true if they are equal.

abPoint(3, 4) #1Point(3, 4) #2a == bfalseObject.equals (default)falseoverridden equalstrue
Figure 4.3.20: Two separate objects with the same content. == and the default equals compare addresses and give false. An overridden equals compares the fields and gives true.

equals cannot be written arbitrarily. The Java library, collections in particular, assumes that equals obeys certain rules. These rules are called the equals contract (Table 4.3.12).

Table 4.3.12: The equals contract (x, y, z are non-null references).
PropertyRule
Reflexivityx.equals(x) → true
Symmetryx.equals(y) ⇔ y.equals(x)
Transitivityif x = y and y = z, then x = z
ConsistencyThe result does not change as long as the fields do not change
nullx.equals(null) → false

These rules are the properties of equality in mathematics. When they are broken, the bugs appear indirectly. If symmetry is broken, list.contains(x) may give true in one order and false in the other. If consistency is broken, an object added to a HashSet cannot be found later.

4.3.7.5equals with instanceof

The parameter of equals has type Object. The object that arrives may not be a Point; it may be a string, a person or null. That is why a type check is made before moving on to the fields:

public boolean equals(Object obj) {
    if (obj instanceof Point) {
        // the object is a Point;
        // cast and compare
        Point other = (Point) obj;
        return x == other.x && y == other.y;
    } else {
        // the object is not a Point;
        // it cannot be equal
        return false;
    }
}

The method first asks with obj instanceof Point whether the incoming object is a Point. If so, it downcasts with (Point) obj. The cast is safe only after the type check. Then it compares the two coordinates. If the object is not a Point, it cannot be equal and false is returned.

Point a = new Point(3, 4);
Point b = new Point(3, 4);
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(a.equals("3,4"));
System.out.println(a.equals(null));
false
true
false
false

The first line compares two separate objects with ==: false. The second compares the contents: true. In the third, "3,4" is not a Point but a String; instanceof gives false and false is returned. Since the cast is never reached, no ClassCastException occurs either. In the fourth, null instanceof Point is false. instanceof always gives false for null. That is why an equals that uses instanceof needs no separate null check.

The parameter type must be Object. Writing equals(Point n) is overloading, not overriding. This mistake escapes the compiler and has insidious results:

class PointA {
    int x, y;
    PointA(int x, int y) { this.x = x; this.y = y; }
    public boolean equals(PointA n) {   // overloading!
        return x == n.x && y == n.y;
    }
}
// in main:
PointA p = new PointA(1, 2), q = new PointA(1, 2);
Object qo = q;
System.out.println(p.equals(q) + " " + p.equals(qo));
List<PointA> list = new ArrayList<>();
list.add(p);
System.out.println(list.contains(q));
true false
false

p.equals(q) gives the right result, because the compile-time type of q is PointA and the compiler chooses equals(PointA). In p.equals(qo), however, the type of the argument is Object. The compiler chooses equals(Object) from Object, which compares addresses: false. Library classes always call equals(Object). That is why ArrayList.contains cannot find a point with the same content. With @Override written, the error would have been caught at compile time: method does not override or implement a method from a supertype.

4.3.7.6equals with getClass(), and a trace

The second way to check the type is getClass():

public class Person {
    private String name;
    private int age;
    // ... constructor ...

    @Override
    public boolean equals(Object obj) {
        // equal if the same reference
        if (this == obj) return true;
        // null or a different class: not equal
        if (obj == null
                || getClass() != obj.getClass())
            return false;
        // compare the fields
        Person person = (Person) obj;
        return age == person.age
               && name.equals(person.name);
    }
}

This pattern has three steps. First this == obj is checked. If it is the same object, there is no need to look at the fields and true is returned at once; this is a quick shortcut. Then obj == null and the class check are made. getClass() gives the actual class of the object; the classes of both sides must be exactly the same. Finally the fields are compared. Primitive types (int age) are compared with ==, fields of object type (String name) with equals.

The two patterns behave differently for subclass objects (Table 4.3.13).

Table 4.3.13: Type checking with instanceof and with getClass().
Type checkCan a subclass object count as equal?
instanceofYes (a Cat object is an Animal)
getClass()No (the classes must be exactly the same)
class Student extends Person {         // Person's equals uses getClass()
    Student(String name, int age) { super(name, age); }
}
// in main:
System.out.println(new Person("Ali", 20).equals(new Student("Ali", 20)));
false

Because the equals of Person uses getClass(), it does not count a Student with the same name and age as equal. With instanceof it would give true. Which one is right depends on the design. getClass() preserves symmetry by itself. instanceof is safe as long as subclasses do not rewrite equals; if a subclass overrides equals with new fields, symmetry can break.

Now let us run the equals with getClass() through a trace:

public boolean equals(Object obj) {
    if (this == obj) return true;
    if (obj == null || getClass() != obj.getClass())
        return false;
    Person person = (Person) obj;
    return age == person.age && name.equals(person.name);
}
// in main:
Person k1 = new Person("Ali", 20);
Person k2 = new Person("Ali", 20);
Person k3 = new Person("Ali", 21);
System.out.println(k1.equals(k2));
System.out.println(k1.equals(k3));
System.out.println(k1.equals(null));
true
false
false
Table 4.3.14: Trace of three equals calls. #1, #2 and #3 are the addresses of the objects.
Callthis == objnull / class checkage == person.agename.equals(...)Result
k1.equals(k2)#1 ≠ #2: falsepassed (Person = Person)20 == 20: true"Ali" = "Ali": truetrue
k1.equals(k3)#1 ≠ #3: falsepassed20 == 21: falsenot called (short circuit)false
k1.equals(null)falseobj == null is true; getClass is not called——false
StackHeapequals()thisobjperson?main()k1k2k3Person #1name"Ali"age20Person #2name"Ali"age20Person #3name"Ali"age21 StackHeapequals()thisobjpersonmain()k1k2k3Person #1name"Ali"age20Person #2name"Ali"age20Person #3name"Ali"age21 StackHeapequals()thisobjpersonmain()k1k2k3Person #1name"Ali"age20Person #2name"Ali"age20Person #3name"Ali"age2120 == 20 true && "Ali".equals("Ali") true StackHeapequals()thisobjpersonmain()k1k2k3Person #1name"Ali"age20Person #2name"Ali"age20Person #3name"Ali"age2120 == 21 false → name.equals is not called
Figure 4.3.21: Four moments of the equals trace. (a) k1.equals(k2): in the new frame this = #1, obj = #2. (b) The downcast does not produce a new object; person refers to the same #2 with type Person. (c) Age and name are equal: true. (d) k1.equals(k3): the ages differ and && short-circuits.

Three details of the trace matter. First, the type of obj is Object. obj.age cannot be written, because Object has no field called age. The downcast gives the reference person, which looks at the same object through a Person window (Figure 4.3.21, b). Second, && short-circuits. If the ages differ, name.equals is never called. That is why writing the cheap comparison first is a good habit. Third, || short-circuits too. If obj == null is true, the right side is not evaluated. Had the order been reversed (getClass() != obj.getClass() || obj == null), obj.getClass() would run with a null argument and a NullPointerException would occur.

In terms of cost, equals compares a fixed number of fields. If one of the fields is a String, its equals does work proportional to the length of the string. The this == obj shortcut skips this work completely in the common case of an object being compared with itself.

4.3.7.7equals and hashCode

Overriding equals carries an obligation. The rule is this: if equals is overridden, hashCode must be overridden too. Equal objects must have the same hashCode values.

Definition 4.3.11

A hash code is the integer that the hashCode() method returns for an object. Its contract: if a.equals(b) is true, then a.hashCode() == b.hashCode() must hold. The converse is not required; two objects that are not equal may have the same hash code.

import java.util.Objects;
public class Point {
    private int x, y;
    public Point(int x, int y) {
        this.x = x; this.y = y;
    }
    @Override public boolean equals(Object o) {
        return (o instanceof Point n)
               && x == n.x && y == n.y;
    }
    @Override public int hashCode() {
        return Objects.hash(x, y);
    }
    @Override public String toString() {
        return "Point[x=" + x + ", y=" + y + "]";
    }
}
HashSet<Point> set = new HashSet<>();
set.add(new Point(3, 4));
set.add(new Point(3, 4));
System.out.println(set.size() + " "
    + set.contains(new Point(3, 4)));
1 true

This Point class overrides all three methods. In equals, the form o instanceof Point n is used. This is pattern matching, available since Java 16: if the check is true, n holds the cast reference. The classic form is if (o instanceof Point) { Point n = (Point) o; … }. hashCode produces a value from the fields with java.util.Objects.hash(x, y).

Why are the two methods needed together? When HashSet and HashMap look for an element, they first choose a “bucket” with hashCode, then call equals only against the elements in that bucket. If hashCode differs, equal objects fall into different buckets and are never compared. Table 4.3.15 compares the two cases.

Table 4.3.15: Output of set.size() + " " + set.contains(new Point(3, 4)).
In class PointOutput
only equals2 false✗
equals + hashCode1 true✓

When only equals is written, the hashCode of Object is used, and in practice it gives two separate objects different values. The second new Point(3, 4) falls into another bucket. The set does not compare it with the first and adds it a second time: size 2. contains looks into a third bucket and does not find it: false. There is no compile error; the compiler does not check that the two methods agree. The bug shows only at run time, with a wrong result.

Common mistake

Overriding equals and forgetting hashCode. The class works without problems in an ArrayList, because ArrayList.contains uses only equals. The bugs start when the same objects are put in a HashSet or used as the key of a HashMap: duplicate elements, keys that cannot be found.

4.3.7.8Code trace: inside a HashSet

How buckets are chosen can be followed with concrete numbers. The code below uses the classic equals form:

public boolean equals(Object o) {
    if (!(o instanceof Point)) return false;
    Point n = (Point) o;
    return x == n.x && y == n.y;
}
public int hashCode() {
    return Objects.hash(x, y);  // 31·(31 + x) + y
}
// in main:
HashSet<Point> set = new HashSet<>();
set.add(new Point(3, 4));
set.add(new Point(4, 3));
set.add(new Point(3, 4));
System.out.println(set.size());
System.out.println(set.contains(new Point(4, 3)));
2
true

Objects.hash(x, y) computes 31 · (31 + x) + y for two fields. An empty HashSet starts with 16 buckets. An element's bucket is hash % 16 for small hash values. (The library actually mixes the upper bits of the hash value into the lower bits and takes hash & 15. For positive values below 65,536 the result is the same as hash % 16.)

Table 4.3.16: Trace of the HashSet. Hash = 31 · (31 + x) + y, bucket = hash % 16.
OperationhashbucketWhat is in the bucket?Resultsize
add(Point(3, 4))31 · 34 + 4 = 10582emptyadded1
add(Point(4, 3))31 · 35 + 3 = 10880emptyadded2
add(Point(3, 4)) (new object)10582(3, 4); equals is truenot added, add returns false2
contains(Point(4, 3))10880(4, 3); equals is truetrue2
set: 16 buckets (bucket = hash % 16)0123456789101112131415(3,4)Point(3,4)31·34 + 4 = 10581058 % 16 = 2 → bucket empty, added set: 16 buckets (bucket = hash % 16)0123456789101112131415(3,4)(4,3)Point(4,3)31·35 + 3 = 10881088 % 16 = 0 → bucket empty, added set: 16 buckets (bucket = hash % 16)0123456789101112131415(3,4)(4,3)Point(3,4) newequals → true3 == 3 && 4 == 4 → true: not added set: 16 buckets (bucket = hash % 16)0123456789101112131415(3,4)(4,3)Point(4,3) new1088 → bucket 0bucket 0 → equals true → foundwithout hashCode: a different bucket, equals is not asked
Figure 4.3.22: Four moments of the HashSet trace. (a) (3, 4): hash 1058, bucket 2. (b) (4, 3): hash 1088, bucket 0. (c) A new (3, 4) again falls into bucket 2; since equals is true, it is not added. (d) contains finds the bucket first, then asks equals: true.

Table 4.3.16 shows two important points. First, the same numbers in a different order give a different hash: 1058 for (3, 4), 1088 for (4, 3). That is why the formula has the factor 31; plain addition (x + y) would send the two points to the same value. Second, the set looks into only one bucket per operation. Searching among elements spread over 16 buckets is much faster than walking through all the elements one by one. With a well-spread hashCode, add and contains take O(1) on average.

Different objects can fall into the same bucket; this is called a collision. The hash of the point (1, 2) is 31 · 32 + 2 = 994, and 994 % 16 = 2. This point falls into the same bucket as (3, 4). In this case the set asks equals, gets the answer false, and adds the new point as the second element of the same bucket. Even the hash values can be equal: the hash of the point (2, 65) is 1088, like that of (4, 3). The contract allows this; equal hashes do not mean equal objects. equals has the last word.

Example 4.3.8

Let the hashCode of a class return 42 for every object, with equals written correctly. After adding (1, 2), (1, 2) and (2, 1) to a HashSet, what is the size? Does the set work correctly?

The contract is not broken: equal objects have the same hash, because all objects have the same hash. All elements fall into the same bucket. The second (1, 2) is caught by equals and not added; (2, 1) is added because it is not equal. The size is 2, and contains answers correctly. But every operation has to walk through all the elements of that single bucket. The set works correctly, but takes O(n) instead of O(1) on average. A bad hashCode breaks not correctness but speed.

4.3.8Common mistakes

Mistakes related to inheritance fall into two groups. Compile errors show up at once with javac's messages. Learning to read the messages lets you fix most of these errors in minutes. Logic errors pass the compiler and are noticed only when the program gives a wrong result. The two tables below gather the mistakes treated separately in the body of these notes. The messages were obtained with the javac and java tools of JDK 21.

Table 4.3.17: Common compile errors related to inheritance.
Mistakejavac messageFix
Not calling super(...) when the superclass has no no-argument constructorconstructor Animal in class Animal cannot be applied to given typessuper(name); on the first line
Not writing super(...) on the first line; writing it together with this(...)call to super must be first statement in constructorA single this/super call, on the first line
Accessing a private field from a subclasshealth has private access in AnimalA getter or a protected method
Accessing a protected member from another package through a supertype referencename has protected access in AnimalAccess through the subclass's own type
Narrowing access when overridingattempting to assign weaker access privileges; was publicThe same or wider access
Changing the return typereturn type String t not compatible with AnimalThe same type or a subtype
Adding a checked exceptionoverridden method does not throw ExceptionCatching the exception inside the method
@Override with a wrong signature: Draw(), equals(Point), a private methodmethod does not override or implement a method from a supertypeExactly the same name and parameter list
Overriding a final methodoverridden method t finalA new method with another name
Deriving from a final classcannot inherit from final FixedComposition
Deriving from two classes'{' expectedComposition or an interface
Calling a subclass method through a supertype variablecannot find symbol … method isWinter()instanceof and a downcast
Table 4.3.18: Common run-time and logic errors related to inheritance.
MistakeResultFix
Comparing objects with ==false for two objects with the same contentequals
equals without hashCodeThe same point is added to a HashSet twice: 2 falseObjects.hash(x, y)
Writing equals(Point) (without @Override)contains cannot find an equal objectequals(Object) and @Override
A typo without @Override (Draw)The superclass version runs silently@Override on every override
Thinking one has overridden a private methodThe superclass code calls its own private version@Override catches this misunderstanding
An unchecked downcastClassCastExceptioninstanceof first
Calling an overridable method from a superclass constructorThe fields of the subclass are still at default values: b=0 s=nullCall only private/final methods from a constructor
Overriding methods that call each other togetherThe counter goes up twice: 6 3Composition and forwarding
Inheritance just to share code (MyStack extends ArrayList)Unwanted public methods come along, insertion in the middle is possibleComposition
A subclass that breaks the promise (Square extends Rectangle)Code written for the superclass gives a wrong result: 16A common superclass or immutable classes

Most of these mistakes are prevented by two habits. The first is writing @Override on every override; it turns three of the first five mistakes in the second table into compile errors. The second is applying the is-a test to the behavior of the class before setting up inheritance. If the test is negative or doubtful, composition is chosen.

4.3.9Summary

  • Inheritance is creating a new class by taking the members of an existing class and adding new ones. It is written class Child extends Parent; only one class follows extends. A class that does not write extends derives from Object.
  • A subclass uses the public and protected members of its superclass as its own. private fields exist in the object but cannot be accessed directly. Constructors are not inherited.
  • new creates a single object; the superclass part is inside this object. super is not a separate object but a way of reaching the same object through the superclass's code.
  • super(...) calls the superclass constructor and in Java 21 is the first statement of the constructor. If it is not written, the compiler inserts super();. super.m() calls the superclass version and is bound at compile time.
  • Constructor calls go from the bottom up, and the bodies complete in the order Object → … → Parent → Child. The order of object construction is: superclass fields, superclass constructor, subclass fields, subclass constructor. static blocks run once, when the class is first used, from the top down.
  • Overriding is rewriting a method with the same signature in the subclass. The actual class of the object decides which version runs. Overloading is a different parameter list and is chosen at compile time.
  • An overriding method cannot narrow the promise of the superclass. The return type is the same or a subtype, the access is the same or wider, and checked exceptions are the same or narrower. @Override has the compiler check these rules.
  • private, static and final methods are not overridden. A method with the same name as a private one is a new method; a static method is only hidden.
  • protected = class + same package + subclasses. A subclass in another package reaches a protected member only through a reference of its own type. Fields stay private, and protected methods are opened to subclasses.
  • A final method cannot be overridden, and no subclass can be derived from a final class (String, Math, Integer).
  • Upcasting happens by itself and narrows the view of the object: the type of the variable determines which methods can be called. A downcast is written explicitly and is first checked with instanceof.
  • is-a is inheritance, has-a is composition. Java does not allow multiple inheritance of classes (the diamond problem); composition and interfaces are used instead.
  • Inheritance brings tight coupling: the fragile base class problem and violations of the substitution principle are its consequences. If the only goal is to share code, composition and forwarding are chosen.
  • Object is the ancestor of every class. toString prints the object readably. equals compares contents and obeys the contract. If equals is overridden, hashCode is overridden too; equal objects have the same hash code.
  • == compares references, equals compares contents. HashSet first chooses a bucket with hashCode, then asks equals; with a good hashCode, operations take O(1) on average.

4.3.10Key terms

  • inheritance
  • superclass / subclass
  • super keyword
  • constructor chaining
  • default constructor
  • initializer block
  • method overriding
  • method overloading
  • method signature
  • annotation
  • covariant return type
  • access modifier
  • upcasting / downcasting
  • dynamic binding
  • is-a / has-a relationship
  • composition
  • multiple inheritance
  • fragile base class
  • forwarding
  • Liskov substitution principle
  • Object class
  • hash code

4.3.11Test Yourself

  1. Given class X { X() { print("X "); } }, class Y extends X { Y() { this(1); print("Y "); } Y(int a) { print("Y" + a + " "); } } and class Z extends Y { Z() { super(5); print("Z "); } }. What does new Z() print?

    Answer

    The first line of Z() is super(5), which calls Y(int) directly; Y() never runs. Y(int) has an implicit super(): first X() runs and prints X. Then the body of Y(int) prints Y5, and last the body of Z() prints Z. Result: X Y5 Z. The text Y is not printed, because the constructor containing this(1) was not called.

  2. Given class P { int f() { return 1; } int g() { return f() * 10; } } and class Q extends P { int f() { return 2; } int g() { return super.g() + 1; } }. What is p.g() for P p = new Q();?

    Answer

    The object is a Q; Q.g() runs and calls P.g() with super.g(). The f() inside P.g() is this.f(), and this is still a Q: Q.f() returns 2. P.g() = 2 · 10 = 20, Q.g() = 20 + 1 = 21. super decides only which version of g is called; the calls inside that version are still chosen by the object. new P().g() gives 10.

  3. Which pairs are is-a and which are has-a relationships? Transistor–Semiconductor device, Circuit–Resistor, Phone–Battery, Vacuum cleaner–Household appliance.

    Answer

    is-a: Transistor–Semiconductor device (“every transistor is a semiconductor device”) and Vacuum cleaner–Household appliance. has-a: Circuit–Resistor (a circuit has resistors; the resistors are kept in a list field) and Phone–Battery (a phone has a battery; the battery can be replaced, which fits the property of composition that the field can be changed later).

  4. Given class U { U() { System.out.println("U(): " + name()); } String name() { return "U"; } } and class V extends U { String s = "V"; String name() { return s; } }. What does new V() print?

    Answer

    U(): null. The implicit super() of V() runs U(). The name() inside U() is overridden, and since the object is a V, it goes to V.name(). But the subclass's field initializers are assigned after super() returns. At that moment s is still null.

  5. The equals of class PersonI uses instanceof PersonI instead of getClass() and compares name and age. StudentI extends PersonI adds no new field and does not override equals. What do new PersonI("Ali", 20).equals(new StudentI("Ali", 20)) and the call in the reverse order give?

    Answer

    Both are true. A StudentI is a PersonI; instanceof is true in both directions and the fields are equal. Symmetry is preserved, because both calls run the same equals. With getClass(), both calls would give false.

  6. Parent has protected Object copy(). Inside Child extends Parent, does @Override public Child copy() compile? Does @Override Child copy() (no modifier) compile?

    Answer

    The first compiles. Child is a subtype of Object (covariant return) and the access widens from protected to public. The second does not compile: writing no modifier means package access, which is narrower than protected. javac says attempting to assign weaker access privileges; was protected.

  7. Do class A { final void f() { … } } and class B extends A { void f(int x) { … } } compile?

    Answer

    They compile. The parameter list of f(int) is different; it does not override A.f(), it overloads it. final forbids only overriding. A B object has both methods: b.f() runs the version of A, b.f(3) the one of B.

  8. animals.Animal has protected String name; animals.Dog extends Animal. In class indoor.Cat extends Animal, in another package, we write String f(Dog k) { return k.name; }. Does it compile?

    Answer

    It does not compile: name has protected access in Animal. A subclass in another package can reach a protected member only through a reference of its own type (Cat or its subtypes). k is a Dog; a cat is not allowed to touch the internal data of a dog. Had Cat been in package animals, it would have compiled.

  9. In a class Point whose hash code is Objects.hash(x, y), (3, 4) and then (1, 2) are added to an empty HashSet. Which buckets do the two points fall into? What is size()?

    Answer

    (3, 4): 31 · 34 + 4 = 1058, 1058 % 16 = 2. (1, 2): 31 · 32 + 2 = 994, 994 % 16 = 2. The two points fall into the same bucket. On the second insertion the set asks equals against the (3, 4) in the bucket, gets false, and adds (1, 2) as well. Both add calls return true; size() = 2. The same bucket does not mean equal objects.

4.3.12Further reading

  • Oracle, The Java Tutorials, the “Inheritance” lesson: covers subclasses, overriding and hiding, super, the Object class and final with short examples. It is Java's official, free starting point.
  • J. Bloch, Effective Java (3rd ed.), Items 10–11 and 18–19: explains how to write equals and hashCode. It also discusses why composition is preferred over inheritance and the rules for designing for inheritance. The fragile base class example comes from this book too.
  • C. S. Horstmann, Core Java, Volume I: Fundamentals (12th ed.), Chapter 5 “Inheritance”: discusses in detail the choice between getClass() and instanceof in equals, and the symmetry problem.
  • OpenJDK, JEP 513 “Flexible Constructor Bodies”: describes the change in Java 25 that allows statements before super(...), and its rationale. It also explains why the constructor rules were introduced.

4.3.13References

  1. Oracle, The Java Tutorials: Inheritance; Overriding and Hiding Methods; Using the Keyword super; Object as a Superclass.
  2. J. Gosling et al., The Java Language Specification, Java SE 21 Edition, Oracle, 2023 (8.1.4 Superclasses and Subclasses, 8.4.8 Inheritance, Overriding, and Hiding).
  3. P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (Chapter 9: Object-Oriented Programming: Inheritance).
  4. K. Sierra and B. Bates, Head First Java, 3rd ed., O'Reilly, 2022 (Chapter 7: Inheritance and Polymorphism).
  5. C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson, 2022 (Chapter 5: Inheritance).
  6. J. Bloch, Effective Java, 3rd ed., Addison-Wesley, 2018 (Items 10–11: equals and hashCode; Item 18: favor composition over inheritance).
  7. OpenJDK, JEP 513: Flexible Constructor Bodies, JDK 25, 2025. https://openjdk.org/jeps/513

Related pages: Chapter 4.3 slides · Study questions · Glossary · © Sercan Külcü. All rights reserved.