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
Loading compiler…
What a subclass gets, and what it does not
- It inherits all
publicandprotectedmembers, plus package-private ones if it is in the same package. - It does not inherit
privatemembers. 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
extendssilently extendsObject.
Paymentabstract settle()
CardPaymentsettle() → gateway
UpiPaymentsettle() → UPI handle
WalletPaymentsettle() → balance
Single inheritance, and the reason for it
A Java class may extend exactly one class but implement any number of interfaces.
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.