Learn / Programming / Java / Inheritance and Polymorphism

Java · Lesson 10 of 15

Inheritance and Polymorphism

extends, super, overriding and treating subclasses as their parent type.

  • Intermediate
  • 15 min read
  • 3 objectives

Before this lessonLesson 9: Methods and Overloading

What you will learn

  • Extend a class
  • Override methods
  • Use polymorphism

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

Inheritance lets a class reuse and extend another. The child (subclass) gets the parent's (superclass's) fields and methods and can add or replace behaviour. Model an is-a relationship: a Dog is an Animal.

extends and super

class Animal {
    protected String name;
    Animal(String name) { this.name = name; }
    String sound() { return "..."; }
    public String toString() { return name + " says " + sound(); }
}

class Dog extends Animal {
    Dog(String name) { super(name); }   // call the parent constructor
    @Override
    String sound() { return "Woof"; }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(new Dog("Rex"));
        System.out.println(new Animal("Thing"));
    }
}
Output
Rex says Woof
Thing says ...

Polymorphism

A variable of the parent type can hold any subclass. Java calls the actual object's version of an overridden method at runtime.

class Animal { String sound() { return "..."; } }
class Dog extends Animal { String sound() { return "Woof"; } }
class Cat extends Animal { String sound() { return "Meow"; } }

public class Main {
    public static void main(String[] args) {
        Animal[] zoo = { new Dog(), new Cat(), new Animal() };
        for (Animal a : zoo) {
            System.out.println(a.sound());
        }
    }
}
Output
Woof
Meow
...

Rules worth remembering

  • A class can extend only one class (single inheritance).
  • Add @Override so the compiler catches typos in method names.
  • final on a class or method forbids extending or overriding it.
  • Every class extends Object, which is where toString, equals and hashCode come from.
Up next · Lesson 11Interfaces and Abstract ClassesContracts, default methods and when to choose an interface or an abstract class.