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:
extendsit 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
privatefields — 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
| Modifier | Visible to |
|---|---|
public | everyone |
protected | same package + any subclass, even in a different package |
| (default, no modifier) | same package only |
private | same 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 withnew; only extended.abstractmethod — no body, must be implemented by every concrete subclass; can't beprivate(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 do | Interface | Abstract class |
|---|---|---|
| Force specific methods | yes | yes |
| Share static members (Java 8+) | yes | — |
| Share default/implemented methods (Java 8+) | yes (default methods) | yes (regular methods) |
| Share instance fields | no | yes |
| A class can have more than one | yes (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).