WeCodeAcademy

Java Inheritance

A class can extend another and inherit its fields and methods. The child can override methods to change behaviour.

ExampleJava
public class Main {
  static class Animal {
    String name;
    Animal(String name) { this.name = name; }
    String speak() { return "..."; }
  }

  static class Dog extends Animal {
    Dog(String name) { super(name); }
    @Override
    String speak() { return name + " says woof"; }
  }

  static class Cat extends Animal {
    Cat(String name) { super(name); }
    @Override
    String speak() { return name + " says meow"; }
  }

  public static void main(String[] args) {
    Animal[] pets = { new Dog("Rex"), new Cat("Tom"), new Animal("Generic") };
    for (Animal a : pets) {
      System.out.println(a.speak());
    }
  }
}
Output
Rex says woof
Tom says meow
...

The loop calls speak() on each Animal, and Java picks the right version for each real object. This is polymorphism: many forms behind one name.

Quick check

Which keyword makes a class inherit from another?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.