Programming with Java
Lesson 2 of 4 9 min +65 XP

Inheritance & Polymorphism

Reusing and extending classes.

What you'll learn

  • Define inheritance
  • Use 'extends' to subclass
  • Explain method overriding
The family recipe, tweaked

Your grandmother's cake recipe gets passed down, and each generation adds its own twist without rewriting the whole thing. Inheritance lets a class build on another, and polymorphism means the same 'bake' instruction can behave differently for each version.

Build on what exists

Inheritance lets one class (the subclass) reuse the fields and methods of another (the superclass) with `extends`. The subclass can add new behavior or override inherited methods to behave differently.

class Animal { void speak() { print("..."); } }
class Dog extends Animal {
  void speak() { print("Woof"); }   // override
}
Lab · Who speaks?
  1. Animal has speak() printing '...'.
  2. Dog extends Animal and overrides speak() to print 'Woof'.
  3. Call speak() on a Dog object.

What you should see: The Dog's overridden speak() runs and prints 'Woof' — that's polymorphism in action.

Knowledge Check

+15 XP / correct

1. Which Java keyword makes one class inherit from another?

2. Redefining an inherited method in a subclass is called…