Lesson 1 of 516 minModule progress 0%

Module 6: Inheritance and Polymorphism

Inheritance Basics with `extends`

Create a subclass that reuses fields and methods from a parent class when there is a true “is-a” relationship.

Author

Java Learner Editorial Team

Reviewer

Technical review by Java Learner

Last reviewed

2026-04-16

Java version

Java 25 LTS

How this lesson was prepared: AI-assisted draft, edited by hand, and checked against current Java 25 documentation and runnable examples.

Learning goals

  • Understand the parent-child class relationship
  • Use `extends` to build a simple subclass
  • Recognize when inheritance fits a real “is-a” idea

Inheritance lets one class reuse another class’s structure: A child class can inherit fields and methods from a parent class.

Use inheritance for true “is-a” relationships: A Dog is an Animal, and a SavingsAccount is an Account.

Why this matters: Shared behavior can live once in the parent class instead of being copied into every child class.

Keep the relationship honest: If the child is not really a more specific version of the parent, inheritance is probably the wrong tool.

Runnable examples

A subclass inherits from a parent class

class Animal {
    String name;

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

class Dog extends Animal {
    void bark() {
        System.out.println("Woof");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.name = "Buddy";
        dog.eat();
        dog.bark();
    }
}

Expected output

Buddy is eating.
Woof

Common mistakes

Using inheritance for a “has-a” relationship

If one class contains or uses another, composition is usually better than inheritance.

Mini exercise

Create a `Vehicle` class and a `Car` class that extends it.

Summary

  • Inheritance models a true “is-a” relationship.
  • `extends` creates the parent-child connection.
  • Child classes inherit useful members from the parent.

Next step

Next, override parent methods so subclasses can provide their own behavior.

Sources used

Advertisement

Lesson check

When is inheritance usually appropriate?

Next lesson →