Object-Oriented JavaExtra· 35 min read

Inheritance (extends)

A class can inherit fields and methods from another class with extends — reusing code.

What you will learn

  • Create a subclass with extends
  • Reuse and add to the parent class
  • Use super to call the parent

Sharing common code

Often classes share things. A Dog and a Cat are both Animals — both have a name and can eat. Rather than repeat that, one class can inherit from another using extends.

The class you inherit from is the parent (or superclass). The class that inherits is the child (or subclass). The child gets all the parent fields and methods for free, then can add its own.

Dog extends Animal and gains its name and eat()
public class Animal {
    String name;

    void eat() {
        System.out.println(name + " is eating.");
    }
}

public class Dog extends Animal {
    void bark() {
        System.out.println(name + " says woof!");   // name comes from Animal
    }
}

Note: Output: (No output yet — these are the classes. Notice Dog never declares name or eat(), yet it can use them because it inherited them from Animal.)

Using the inherited members

A Dog can do both Animal things and Dog things
public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.name = "Rex";
        d.eat();    // inherited from Animal
        d.bark();   // Dog's own method
    }
}

Note: Output: Rex is eating. Rex says woof! eat() came from the Animal parent, while bark() is Dog own. One Dog object happily uses both. That is code reuse through inheritance.

The keyword super

A child can call the parent constructor or methods with super. This is common in constructors:

super passes values up to the parent constructor
public class Animal {
    String name;
    Animal(String name) { this.name = name; }
}

public class Dog extends Animal {
    Dog(String name) {
        super(name);   // call Animal's constructor
    }
}

Note: Output: (No output — this shows the pattern. super(name) runs the Animal constructor first, so the inherited name field gets set correctly.)

Tip: A good test for inheritance is the words is a. A Dog is an Animal, so Dog extends Animal makes sense. If you cannot say is a, inheritance is probably the wrong tool.

Q. If Dog extends Animal and Animal has a method eat(), can a Dog object call eat()?

Answer: A subclass inherits the public fields and methods of its parent, so a Dog automatically has Animal eat() without rewriting it.

✍️ Practice

  1. Create a Vehicle class with a start() method, and a Car subclass that adds honk().
  2. Make a Car object and call both methods.

🏠 Homework

  1. Build a Shape parent class and two children (Circle, Square) that each add their own method. Show one object of each.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →