Board Formulas
β˜• JavaπŸ“… Day 14

Inheritance in Java

Reuse code by building a child class on top of a parent class with extends, call the parent with super, and override methods.

🎯

Learning objectives

  • β†’Create a subclass with extends and reuse the parent's fields and methods
  • β†’Use super to call the parent's constructor and methods
  • β†’Override a method with @Override to change inherited behaviour
  • β†’Name the types of inheritance Java supports with classes, and the one it does not

πŸ’‘ Key points

  • Inheritance lets a new class (subclass or child) reuse the fields and methods of an existing class (superclass or parent) through extends.
  • It models an IS-A relationship: a Student IS-A Person, a Bike IS-A Vehicle.
  • Constructors are not inherited. A child constructor calls the parent's with super(...), which must be its first statement.
  • If you don't write super(...), Java inserts super() for you, so the parent then needs a no-arg constructor.
  • Overriding means the child redefines a method with the same name and parameters. @Override asks the compiler to check that you really are overriding.
  • super.method() calls the parent's version of a method from inside the child.
  • With classes, Java supports single, multilevel and hierarchical inheritance, but not multiple (extends A, B). Every class ultimately extends Object.

πŸ’» Code examples(5)

#1extends: reuse a parent's code
java
class Person {
    String name;
    int age;

    void introduce() {
        System.out.println("I am " + name + ", " + age);
    }
}

class Student extends Person {
    int rollNo;

    void study() {
        System.out.println(name + " is studying");
    }
}

public class InheritDemo {
    public static void main(String[] args) {
        Student s = new Student();
        s.name = "Priya";     // from Person
        s.age = 16;           // from Person
        s.rollNo = 21;        // Student's own
        s.introduce();        // inherited method
        s.study();
    }
}
Output
I am Priya, 16
Priya is studying
Student gets name, age and introduce() from Person without retyping them, and adds rollNo and study() of its own.
#2super(): calling the parent constructor
java
class Person {
    String name;

    Person(String name) {
        this.name = name;
        System.out.println("Person constructor");
    }
}

class Teacher extends Person {
    String subject;

    Teacher(String name, String subject) {
        super(name);              // must be first
        this.subject = subject;
        System.out.println("Teacher constructor");
    }
}

public class SuperDemo {
    public static void main(String[] args) {
        Teacher t = new Teacher("Mrs. Iyer", "Physics");
        System.out.println(t.name + " teaches "
            + t.subject);
    }
}
Output
Person constructor
Teacher constructor
Mrs. Iyer teaches Physics
super(name) passes name up to Person's constructor, so the parent part of the object is set up first. Without it, Java would insert super() and fail, because Person has no no-arg constructor.
#3Overriding with @Override and super.method()
java
class Vehicle {
    int wheels() {
        return 4;
    }

    String describe() {
        return "A vehicle";
    }
}

class Bike extends Vehicle {
    @Override
    int wheels() {
        return 2;
    }

    @Override
    String describe() {
        return super.describe() + " with "
            + wheels() + " wheels";
    }
}

public class OverrideDemo {
    public static void main(String[] args) {
        Vehicle v = new Vehicle();
        Bike b = new Bike();
        System.out.println(v.describe());
        System.out.println(b.describe());
    }
}
Output
A vehicle
A vehicle with 2 wheels
Bike replaces wheels() completely. In describe() it reuses the parent's text through super.describe() and then adds to it.
#4Multilevel inheritance and constructor order
java
class Animal {
    Animal() {
        System.out.println("1. Animal");
    }
}

class Mammal extends Animal {
    Mammal() {
        System.out.println("2. Mammal");
    }
}

class Dog extends Mammal {
    Dog() {
        System.out.println("3. Dog");
    }
}

public class OrderDemo {
    public static void main(String[] args) {
        new Dog();
    }
}
Output
1. Animal
2. Mammal
3. Dog
Dog extends Mammal, and Mammal extends Animal, so this is multilevel inheritance. Every constructor quietly starts with super(), so construction runs from the top of the chain down.
#5Hierarchical inheritance: a payroll
java
class Employee {
    String name;
    double baseSalary;

    Employee(String name, double baseSalary) {
        this.name = name;
        this.baseSalary = baseSalary;
    }

    double salary() {
        return baseSalary;
    }

    void printSlip() {
        System.out.println(name + ": Rs." + salary());
    }
}

class Manager extends Employee {
    double bonus;

    Manager(String name, double base, double bonus) {
        super(name, base);
        this.bonus = bonus;
    }

    @Override
    double salary() {
        return baseSalary + bonus;
    }
}

class Intern extends Employee {
    Intern(String name, double stipend) {
        super(name, stipend);
    }
}

public class Payroll {
    public static void main(String[] args) {
        new Employee("Ravi", 30000).printSlip();
        new Manager("Anita", 50000, 10000).printSlip();
        new Intern("Rohan", 12000).printSlip();
    }
}
Output
Ravi: Rs.30000.0
Anita: Rs.60000.0
Rohan: Rs.12000.0
Manager and Intern both extend Employee (hierarchical). printSlip() is written only once, but Manager overrides salary(), so Anita's slip includes her bonus.

🎯 Practice

Q1. Which keyword makes Dog a subclass of Animal?+

extends. Write class Dog extends Animal { ... }

Q2. Why does this fail? class A { A(int x) { } } class B extends A { B() { } }+

B() silently calls super(), but A has no no-arg constructor, so the error is 'constructor A in class A cannot be applied to given types'. Fix it by writing super(5); (any int) as the first line of B(), or by adding A() { } to A.

Q3. Can a Java class extend two classes, as in class C extends A, B?+

No. Java does not allow multiple inheritance with classes, which avoids confusion when both parents have the same method. A class can implement several interfaces instead (Day 16).

Q4. What is printed by new Q().show()? class P { void show() { System.out.println("P"); } } class Q extends P { @Override void show() { super.show(); System.out.println("Q"); } }+

Two lines, P and then Q. super.show() runs the parent's version first, then Q prints its own line.

Q5. You meant to override show() but typed shwo() with @Override above it. What happens?+

The compiler reports 'method does not override or implement a method from a supertype'. Without @Override, you would silently get a new method and the old show() would still run.

πŸ“ Notes

What a subclass gets

  • Fields and methods: yes, unless they are private. Private fields still exist inside the child object, but the child cannot name them directly. Trying gives secret has private access in P. Use the parent's methods instead (Day 17).
  • Constructors: no. Call them with super(...).
  • Its own extras: a child can add new fields and methods, and override inherited ones.

Types of inheritance in Java

  • Single: class B extends A
  • Multilevel: class C extends B, where class B extends A
  • Hierarchical: class B extends A and class C extends A
  • Multiple: class C extends A, B is not allowed with classes. It becomes possible with interfaces (Day 16).

Every class extends Object

A class with no extends secretly extends java.lang.Object. That is where toString() and equals() come from, and you can override them:

class Book {
    String title = "Wings of Fire";

    @Override
    public String toString() {
        return "Book: " + title;
    }
}
// System.out.println(new Book());  β†’ Book: Wings of Fire

Common mistakes

  • Statements before super(...). It must be first, otherwise you get call to super must be first statement in constructor.
  • Skipping @Override. A typo in the name then creates a new method instead of overriding the old one.
  • Using inheritance for HAS-A. A Car has an Engine, so it should hold an Engine field, not extends Engine. Ask "is it a kind of?" before using extends.

Next: Day 15, Polymorphism. One method call can behave differently depending on the object behind it.