Skip to main content
PreparationZone Logo
PrepZone

Inheritance and Composition

extends, super and this — plus the judgement call about when not to inherit at all.

Pass checkpoint below

Read these first

Why this matters

  • Inheritance is the most over-used feature in object-oriented code, and the resulting hierarchies are the hardest thing to refactor later.
  • "Favour composition over inheritance" is advice everyone repeats and few can justify. The justification is specific and worth knowing.
  • Java's single-inheritance rule forces a design decision early, so understanding the trade-off is not optional.

How inheritance works

Java
Loading compiler…

What a subclass gets, and what it does not

  • It inherits all public and protected members, plus package-private ones if it is in the same package.
  • It does not inherit private members. They exist in the object but are unreachable by name.
  • It does not inherit constructors. It must call one of the parent's via super(...).
  • super.method() calls the parent's version, which is how you extend behaviour rather than replace it.
  • Every class without an explicit extends silently extends Object.
Paymentabstract settle()
CardPaymentsettle() → gateway
UpiPaymentsettle() → UPI handle
WalletPaymentsettle() → balance
Each subclass keeps the Payment contract but supplies its own settle() body. Calling settle() on a Payment variable runs the subclass version.

Single inheritance, and the reason for it

A Java class may extend exactly one class but implement any number of interfaces.

Java
Loading compiler…

The reason is the diamond problem. If a class inherited concrete state and behaviour from two parents that both defined start(), there would be no principled way to decide which runs. Interfaces avoid this because, historically, they carried no implementation at all.

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 5 sections

  • Composition
  • Why composition usually wins
  • When inheritance is the right answer
  • this and super
  • Common misreadings

Test yourself

Answer these before moving on — recall is what makes it stick.