New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› Java› Inheritance, Interfaces and Polymorphism

Inheritance, Interfaces and Polymorphism

💻 Java

Share behaviour through inheritance and define contracts with interfaces.

Lesson 7 of 9 Tutorial
0 of 9 completed

Inheritance reuses a parent class. Interfaces describe what a class can do without saying how. Polymorphism lets one type stand in for many.

By the end of this lesson you can:
  • Extend a class.
  • Implement an interface.
  • Use polymorphism in a list.

Inheritance

A subclass extends a parent and can override methods. Use super to call the parent constructor.

class Animal {
    protected String name;

    Animal(String name) {
        this.name = name;
    }

    String sound() {
        return "...";
    }
}

class Dog extends Animal {
    Dog(String name) {
        super(name);
    }

    @Override
    String sound() {
        return "Woof";
    }
}

Interfaces

An interface lists methods a class must provide. A class can implement several interfaces, which avoids the single-parent limit of inheritance.

interface Gradable {
    String grade();
}

class Assignment implements Gradable {
    private int score;

    Assignment(int score) {
        this.score = score;
    }

    public String grade() {
        return score >= 50 ? "Pass" : "Fail";
    }
}

Polymorphism

A variable typed as the parent or interface can hold any implementing object. The correct override runs at runtime.

Animal[] animals = { new Dog("Rex"), new Animal("Unknown") };

for (Animal animal : animals) {
    System.out.println(animal.name + ": " + animal.sound());
}
Warning Prefer composition over deep inheritance. A five-level class hierarchy is hard to change safely.

Practice

  1. Create a Shape parent with an area method.
  2. Add Circle and Rectangle subclasses.
  3. Define a Drawable interface and implement it in two classes.

Hands-on exercise

Create an interface Shape with area().
Implement Circle and Rectangle.
Put both in a Shape array and print each area rounded to two decimals.

Recap

Inheritance shares code, interfaces define contracts and polymorphism lets one type handle many implementations.

Example

class Animal {
    protected String name;

    Animal(String name) {
        this.name = name;
    }

    String sound() {
        return "...";
    }
}

class Dog extends Animal {
    Dog(String name) {
        super(name);
    }

    @Override
    String sound() {
        return "Woof";
    }
}

Exercises

Exercise 1. Shapes Hard
Create an interface Shape with area().
Implement Circle and Rectangle.
Put both in a Shape array and print each area rounded to two decimals.
Java exercise-1.java
Expected Output
28.27
20.00

Lesson Nav

Lesson sections