Inheritance

A subclass takes the fields and methods of its parent and adds or replaces some. It is the right tool for a true is-a relationship and the wrong one for sharing code.

Overview

Inheritance lets one class (the subclass) be defined in terms of another (the superclass). The subclass starts with the parent's members and can add new ones or override the ones it inherits. A SavingsAccount is an Account with an interest rate; a CheckingAccount is an Account with an overdraft limit. Code written for Account works on both.

Interviewers use inheritance questions to check two things. First, that you know the mechanics: what is inherited, what overriding means, how a call is resolved. Second, and more important, that you know when not to use it. Most inheritance in real codebases is there to reuse code, not to model an is-a relationship, and that is where the fragile hierarchies come from.

A subclass is a special case of its parent

The account example draws as a small tree, with Account at the top and its two special cases below it.

What exactly comes down the arrow is language-specific, and Java's rules are the ones interviewers expect you to know.

  • Public and protected members: inherited, whatever package the subclass is in.
  • Package-private members: inherited only if the subclass is in the same package.
  • Private members: not inherited. The subclass can reach them only through the parent's methods.
  • Constructors: not inherited. The subclass calls one with super(...).
  • Static members: inherited, but a static method with the same signature hides the parent's method; it does not override it.

Every Java class except Object has exactly one direct superclass. Python and C++ allow several, which is covered below.

Interview questions

  • What is the difference between overriding and overloading?
  • When should you prefer composition over inheritance?
  • What does the Liskov substitution principle require of a subclass?
  • How do access modifiers interact with inheritance?
  • How do you stop a class from being extended, and why would you?
  • How does Python decide which method runs with multiple inheritance?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio