Java Inheritance & Polymorphism

extends, super and overriding.

✍️ 2 exercises in this lesson
  • Inheritance: class Dog extends Animal gets Animal's fields and methods.
  • super calls the parent's constructor or methods.
  • @Override marks a method that replaces a parent method.
  • Polymorphism: a parent-type variable can hold any child object, and the child's version of the method runs.
  • final classes cannot be extended.

Key Takeaways: Java Inheritance & Polymorphism

Mastering Java Inheritance & Polymorphism helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Java Inheritance & Polymorphism Code Example

Java
class Animal {
    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"; }
}

class Cat extends Animal {
    Cat(String name) { super(name); }
    @Override String sound() { return "Meow"; }
}

public class Main {
    public static void main(String[] args) {
        Animal[] pets = {new Dog("Moti"), new Cat("Billo")};
        for (Animal a : pets) {
            System.out.println(a.name + " says " + a.sound());
        }
    }
}
Output
Moti says Woof
Billo says Meow
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Java Inheritance & Polymorphism Practice Exercises

Check what you learned in “Java Inheritance & Polymorphism”.

/ 2 solved
Fill in the blank

Inherit from Animal.

class Dog  Animal { }
✓ Correct! Not quite. Try again.
Multiple choice

Which annotation marks a method that replaces a parent method?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services