Skip to content
Justice Tech School

Inheritance

extends makes a class inherit fields and methods from a parent. super calls the parent constructor or method. @Override marks a method that replaces the parent version. A class can extend only one class.

Example
class Animal {
  void speak() { System.out.println("Some sound"); }
}

class Dog extends Animal {
  @Override
  void speak() {
    super.speak();
    System.out.println("Woof");
  }
}

public class Main {
  public static void main(String[] args) {
    new Dog().speak();
  }
}

Result

Some sound
Woof

Exercise

Inherit from Animal.

class Dog  Animal {}

Quiz Test

How many classes can a class extend?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.