Java ยท Chapter 26 of 42

Java Inheritance

Inheritance lets a class (subclass) acquire fields and methods from another class (superclass), using the `extends` keyword. This promotes code reuse and models 'is-a' relationships.

A subclass can add new fields/methods and override inherited methods to provide specialized behavior, using the `super` keyword to reference the parent class.

Syntax
class Sub extends Super {
  Sub() { super(); }
}

extends keyword

Class B extends class A to inherit its non-private members. B is called the subclass (or child), A is the superclass (or parent).

super keyword

super() calls the parent's constructor, and super.method() calls the parent's version of an overridden method.

Example 1 (java)
class Animal {
  void eat() { System.out.println("This animal eats food"); }
}
class Dog extends Animal {
  void bark() { System.out.println("Woof!"); }
}
public class Main {
  public static void main(String[] args) {
    Dog d = new Dog();
    d.eat();
    d.bark();
  }
}
Output
This animal eats food
Woof!

Dog inherits eat() from Animal and adds its own bark() method.

Key points

  • extends creates a subclass that inherits from a superclass.
  • Subclasses inherit non-private fields and methods.
  • super() calls the parent constructor.
  • Inheritance models 'is-a' relationships.
๐Ÿ’ก Note: Java supports single inheritance for classes โ€” a class can extend only one superclass.

๐Ÿ“ Quick Quiz

1. Which keyword creates inheritance between classes?

2. What does super() call?

3. How many classes can a Java class extend?