codegurukool.com · Free coding tutorials & online compiler

Home › Java Tutorial › Java inheritance

Java inheritance

Children reuse and extend parents.

Use extends to inherit fields and methods from a parent class. A child can override a method (mark it @Override) and call the parent's version with super. A class can extend only one class.

Example code

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

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

public class Main {
  public static void main(String[] args) {
    Animal a = new Animal();
    a.speak();
    Cat c = new Cat();
    c.speak();
  }
}

Run this code in the online editor

← Java encapsulationJava polymorphism →