Skip to content

Inheritance & abstract classes — cheat sheet ​

From: fundamentals/18-abstract-classes.md, fundamentals/19-inheritance.md.

Inheritance ​

  • Superclass/parent: holds code to be shared. Subclass/child: extends it and reuses that code.
  • Subclass constructor's first line must call super(...) with whatever the superclass constructor needs.
  • A subclass can't directly touch the superclass's private fields — only through whatever public/protected members the superclass exposes.
  • Multiple subclasses of the same superclass can all be stored in a List<Superclass> — same polymorphism benefit as with interfaces.

The four visibility levels ​

ModifierVisible to
publiceveryone
protectedsame package + any subclass, even in a different package
(default, no modifier)same package only
privatesame class only

protected is specifically the one meant for sharing with subclasses outside the package — otherwise identical to default/package visibility.

Abstract classes ​

  • abstract class — can't be instantiated with new; only extended.
  • abstract method — no body, must be implemented by every concrete subclass; can't be private (a private method can't be overridden anyway).
  • A regular (non-abstract) method inside an abstract class is inherited/shared as normal, same as any other class.
  • Think of it as: "some behavior is common to every subclass and lives here directly; some behavior is required but differs per subclass, so it's declared abstract and filled in by each one."

Interfaces vs abstract classes ​

Can doInterfaceAbstract class
Force specific methodsyesyes
Share static members (Java 8+)yes—
Share default/implemented methods (Java 8+)yes (default methods)yes (regular methods)
Share instance fieldsnoyes
A class can have more than oneyes (multiple implements)no (single extends)

Rule of thumb for an interview: reach for an interface when you're defining a capability/contract that unrelated classes might implement (Vehicle, RandomNumberGenerator); reach for an abstract class when there's real shared state or implementation among closely related classes, and "is-a" makes sense (Animal → Dog/Cat).