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.
Concept 1 of 6
Inheritance: the is-a relationship
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
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 superclass | Inherited? | Usable in the subclass? |
|---|---|---|
| public / protected fields and methods | Yes | Yes, directly |
| default (package) members | Yes | Only if the subclass is in the same package |
| private fields | They exist inside the object | No — use public/protected getters and setters |
| constructors | No | Called with super(...) |
| static members | Shared, not copied | Yes, through the class name |
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.fieldreaches 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());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
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();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
The Object class
| Method of Object | Default behaviour | Usually override? |
|---|---|---|
toString() | Student@1b6d3586 | Yes, to print useful text |
equals(Object o) | Same as == (same object?) | Yes, to compare contents |
hashCode() | Based on identity | Yes, whenever you override equals |
getClass() | Run-time class | No (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
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
Worked example 2 of 3
Worked example 2
class P { P(int x) {} } class Q extends P { Q() {} }Show the solution
super(), but P has no no-arg constructor. Fix: Q() { super(0); }.Worked example 3 of 3
Worked example 3
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.
class C extends A, B?Show the answer
Show the answer
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.
System.out.println(obj) print if the class does not override toString()?Show the answer
Student@7a81197d.Show the answer
new C() in A → B → C?Show the answer
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.