Home
7Inheritance
7

Topic 7 of 13 · Lectures 9–10

Inheritance

Building new classes from existing ones with extends, drawing the hierarchy in UML, using super for constructors and members, multilevel hierarchies and the Object class.

← → move between slides · F full screen · M slide list

Before we start

Why this matters

A university system has Students, Teachers and Staff. All of them have a name, age, phone number and address. Do you really write those four fields three times?

Inheritance lets you put the shared parts in one superclass (Person) and have each subclass add only what is different. Fix a bug in Person and all three classes are fixed.

You will also see exactly which constructors run, and in what order, when you create an object at the bottom of a hierarchy.

Outline · Lectures 9–10

Topics in this chapter

Select a topic to jump to the slide that explains it.

  1. Inheritance basics and UML
  2. Using super
  3. Multilevel hierarchy and constructor order
  4. The Object class

Concept 1 of 6

Inheritance: the is-a relationship

UML: the hollow triangle points from the subclass to its superclass.

Inheritance: the is-a relationship

class Person {
    protected String name;
    protected int age;
    String introduce() { return "I am " + name; }
}
class Student extends Person {
    private double cgpa;              // added
    void study() { System.out.println(name + " studies"); }
}
  • class Student extends Person: a Student is a Person.
  • The subclass inherits all accessible fields and methods and can add its own.
  • Test with “is-a”: a Car is a Vehicle ✓, a Car is an Engine ✗ (a Car has an Engine).

Concept 2 of 6

Types of inheritance

Java classes support single, multilevel and hierarchical inheritance. Multiple inheritance of classes is not allowed.

Concept 2 of 6

Types of inheritance (cont.)

  • A Java class extends exactly one superclass (by default Object).
  • Multiple inheritance of classes is banned to avoid the diamond problem (two inherited versions of the same method).
  • A class can implement many interfaces — that is how Java gets the benefits of multiple inheritance (topic 9).

Concept 3 of 6

What a subclass can and cannot use

Member of the superclassInherited?Usable in the subclass?
public / protected fields and methodsYesYes, directly
default (package) membersYesOnly if the subclass is in the same package
private fieldsThey exist inside the objectNo — use public/protected getters and setters
constructorsNoCalled with super(...)
static membersShared, not copiedYes, through the class name
Why it matters: Private fields are still part of every Student object — Student just cannot name them. That is why Student’s constructor must call super(name, age) to set them.

Concept 4 of 6

The super keyword

class Person {
    private String name;
    Person(String name) { this.name = name; }
    String getName() { return name; }
    String introduce() { return "I am " + name; }
}
class Student extends Person {
    private int id;
    Student(String name, int id) {
        super(name);                 // 1. superclass constructor
        this.id = id;
    }
    @Override

Concept 4 of 6

The super keyword (cont.)

    String introduce() {
        return super.introduce()     // 2. superclass version
               + ", ID " + id;
    }
}
  • super(args) calls the superclass constructor; it must be the first statement.
  • If you do not write it, the compiler inserts super(); — which fails if the superclass has no no-arg constructor.
  • super.method() calls the superclass version of an overridden method.
  • super.field reaches a superclass field hidden by a subclass field with the same name.

Code example

super in action

class Person { private String name; Person(String name) { this.name = name; } String introduce() { return "I am " + name; } } class Student extends Person { private int id; Student(String name, int id) { super(name); this.id = id; } @Override String introduce() { return super.introduce() + ", ID " + id; } } class Teacher extends Person { private String dept; Teacher(String name, String dept) { super(name); this.dept = dept; } @Override String introduce() { return super.introduce() + " from " + dept; } } Person[] people = { new Student("Mitu", 221), new Teacher("Dr. Karim", "CSE") }; for (Person p : people) System.out.println(p.introduce());
Output
I am Mitu, ID 221
I am Dr. Karim from CSE

Step through the code

Trace: super(…) and super.introduce()

Follow one object through two constructors, then see an override call the superclass version with super.

Step through the code

Trace: super(…) and super.introduce() (cont.)

Concept 5 of 6

Multilevel hierarchies and constructor order

A three-level hierarchy: ElectricCar → Car → Vehicle.

Concept 5 of 6

Multilevel hierarchies and constructor order (cont.)

class Vehicle {
    Vehicle() { System.out.println("Vehicle"); }
}
class Car extends Vehicle {
    Car() { System.out.println("Car"); }
}
class ElectricCar extends Car {
    ElectricCar() { System.out.println("ElectricCar"); }
}
new ElectricCar();
Output
Vehicle
Car
ElectricCar

Constructors run from the top of the hierarchy down: a superclass part must be ready before the subclass part is built.

Step through the code

Trace: constructor chaining

Each constructor first calls super(). Watch the frames stack up to A, then print on the way back down.

Step through the code

Trace: constructor chaining (cont.)

Concept 6 of 6

The Object class

Every class inherits from java.lang.Object, directly or indirectly.

The Object class

Method of ObjectDefault behaviourUsually override?
toString()Student@1b6d3586Yes, to print useful text
equals(Object o)Same as == (same object?)Yes, to compare contents
hashCode()Based on identityYes, whenever you override equals
getClass()Run-time classNo (final)

Design

Inheritance vs composition (is-a vs has-a)

class Engine {
    int hp;
    Engine(int hp) { this.hp = hp; }
    void start() { System.out.println(hp + " hp engine started"); }
}
class Car extends Vehicle {       // is-a: inheritance
    private Engine engine;        // has-a: composition
    Car(int hp) { engine = new Engine(hp); }
    void drive() {
        engine.start();           // delegate
        System.out.println("driving");
    }
}
  • Inheritance (is-a) reuses the superclass’s interface and code.
  • Composition (has-a) keeps an object as a field and delegates work to it.
  • Prefer composition when the relationship is not a true “is-a”: a Stack is not an ArrayList, but it can have one.

Worked example 1 of 3

Worked example 1

What is printed?
class A { A() { System.out.print("A"); } }
class B extends A { B() { System.out.print("B"); } }
class C extends B { C() { super(); System.out.print("C"); } }
new C();
Show the solution
ABC. Every constructor calls its superclass constructor first.

Worked example 2 of 3

Worked example 2

Why does this fail? class P { P(int x) {} } class Q extends P { Q() {} }
Show the solution
Q() implicitly calls super(), but P has no no-arg constructor. Fix: Q() { super(0); }.

Worked example 3 of 3

Worked example 3

Draw the UML and write the classes: Shape has color; Circle is a Shape with radius; both have constructors.
Show the solution
class Shape {
    protected String color;
    Shape(String color) { this.color = color; }
}
class Circle extends Shape {
    private double radius;
    Circle(String color, double radius) {
        super(color);
        this.radius = radius;
    }
}
UML: Circle → (hollow triangle) → Shape.

Practice

Practice (1 of 2)

Try each one on paper first, then check your answer.

1. Why does Java not allow class C extends A, B?
Show the answer
To avoid the diamond problem: if A and B both define the same method, C would inherit two conflicting versions. Interfaces are used for multiple inheritance of type.
2. Can a subclass access a private field of its superclass directly?
Show the answer
No. The field is inherited (it is inside the object) but not accessible; use a protected or public getter/setter.
3. Write Manager extends Employee with an extra bonus, overriding salary() using super.salary().
Show the answer
class Manager extends Employee {
    private double bonus;
    Manager(String n, double base, double bonus) { super(n, base); this.bonus = bonus; }
    @Override double salary() { return super.salary() + bonus; }
}

Practice

Practice (2 of 2)

Try each one on paper first, then check your answer.

4. What does System.out.println(obj) print if the class does not override toString()?
Show the answer
ClassName@hexHashCode, e.g. Student@7a81197d.
5. Name the relationship: Library – Book, Dog – Animal, Car – Wheel, Square – Rectangle.
Show the answer
has-a, is-a, has-a, is-a (with care: a Square “is a” Rectangle mathematically, but changing width alone breaks it — a classic design trap).
6. In which order do constructors and field initialisers run for new C() in A → B → C?
Show the answer
A’s fields and constructor, then B’s, then C’s — from the top of the hierarchy down.

Check yourself

Quiz

Summary

Summary

  • extends creates an is-a relationship; the subclass inherits accessible members and adds its own.
  • Java classes have exactly one superclass; multiple inheritance comes through interfaces.
  • super(...) calls the superclass constructor (first statement); super.m() calls the superclass version of m.
  • Constructors run from the top of the hierarchy down.
  • Every class inherits toString, equals and hashCode from Object.