beginnerFree

Inheritance

extends - child class inherits from parent

Inheritance

Inheritance lets you reuse code. A subclass inherits non-private parent members and can override methods.

The narrated version of this skribble — tap play for the full-size video.

0:00 / 1:20

The Big Picture

Inheritance lets a class acquire fields and methods from another using extends. It models "is-a" relationships.

  • Subclass inherits all non-private members
  • Common: HttpServlet, JPanel, Exception
  • Java allows single inheritance only (one superclass)

Enables code reuse and polymorphic behavior.

How It Works

Creating a subclass instance runs superclass constructor first (via super()), then subclass constructor.

  • @Override replaces inherited method behavior
  • super.method() calls parent version
  • Method calls check runtime type (dynamic dispatch)
  • Fields are not polymorphic - resolved at compile time

In the Java Landscape

One of the four OOP pillars, closely tied to polymorphism.

  • Abstract classes provide partial implementations
  • final classes (String, Integer) block inheritance
  • Sealed classes (Java 17+) permit specific subclasses
  • Modern Java favors composition and interfaces
  • Interfaces provide multiple-inheritance of behavior

Pitfalls and Best Practices

  • Don't inherit just to reuse code - use composition
  • Liskov: subclass must work wherever parent does
  • Mark methods final if subclasses shouldn't override
  • Avoid deep hierarchies (>3 levels gets brittle)
  • Document protected methods - they're part of your API
#java#oop#inheritance