Lesson · Inheritance & Polymorphism
Inheritance: a class that starts from another
17 min readInheritance
extends says IS-A: the subclass receives everything the parent offers, parents build first in the constructor chain, and every class ultimately starts from Object. One keyword removes the copy-paste tax between related types.
The copy-paste tax
Two classes in a company tool carry the same members, copied by hand:
class Employee { String name; int salary; String label() { return "Employee " + name; } } class Manager { String name; // copied from Employee int salary; // copied again int teamSize; String label() { return "Employee " + name; } // and again }
Predict: salary rules change next sprint. How many places must change, and what happens the day someone updates one copy and forgets the other? A manager is a kind of employee; the language can say that in one keyword instead of copying.
extends says IS-A
Write class Manager extends Employee and Manager keeps every member Employee offers, adds its own, and gains a relationship: a Manager IS-A Employee. The words for the two sides:
| Word | Means | In our example |
|---|---|---|
| superclass | The class being extended (the parent) | Employee |
| subclass | The class that extends (the child) | Manager |
| IS-A | Every Manager can stand in wherever an Employee is expected | Employee e = m; is legal |
- Comes along: the parent's fields and methods, except
privateones. They travel in every object; only direct access stays off-limits for the child. - Stays home: constructors are never inherited, and
privatemembers cannot be touched directly by the child even though they exist inside its objects. - One parent only:
extends Anames a single superclass. Chains are allowed (Manager extends Employee extends Object), and many types from one class comes later with interfaces. - Object is the root: every class you ever write extends Object, written or not. That is where
toString,equalsandgetClasscome from.
Inheritance is a sentence about identity, not about code reuse. 'A manager is an employee' is true in every meeting; if the sentence needs 'has' instead ('a car has an engine'), you want a field, not extends.
Parents build first
A Manager object contains the Employee part and the Manager part, so construction runs in two rounds, parent first:
new Manager("Ada", 5000, 3)reserves one object whose fields cover both classes.- Every field starts at its default (
null,0): the object exists before any constructor code runs. - Manager's constructor starts by calling
super(name, salary), so the parent's constructor runs first and fills the Employee part. - Only then does the rest of Manager's constructor run, setting
teamSize. Parents finish before children complete.
`super(...)` must be the first statement when you write it, and is called implicitly when you omit it. The one catch: if the parent has no no-argument constructor and you never call super, the compiler refuses. The error reads: constructor Employee in class Employee cannot be applied to given types.
One object, two constructors · parent first
Current statement
Hierarchy
Object · Manager #1
reservedOne object holds the fields of both classes; two constructors fill it in turn.
new Manager("Ada", 5000, 3) starts the build. The runtime reserves one object whose fields cover both classes: Employee's fields and the Manager extras.
Should this be inheritance?
Before typing extends, run the sentence test and the checklist:
- Say it out loud: 'a X is a Y'. If a customer would nod ('a manager is an employee'), inheritance is a candidate.
- If the honest sentence is 'a X has a Y' ('a car has an engine'), make it a field instead; that is composition, and it is the common answer.
- Reusing a method is not a reason by itself. Inheritance promises identity forever; if you only wanted the code, copy is cheaper than a false relationship.
- Check the members you need:
privateparent members will not open, so plan a getter or rethink the boundary. - Keep the chain short and honest. Two or three levels of real IS-A relations read well; ten levels of 'convenience' do not.
The test is a sentence, not a diagram. If 'is-a' is true, extends fits; if 'has-a' is true, a field fits. The rest of the design chapter builds on getting that one word right.
A subclass starts from its parent, and parents build first
extends grants the IS-A relationship and every inheritable member in one keyword. Construction is a chain: fields default, the parent's constructor runs, the child's finishes the job. Keep the relationship honest: a sentence that uses 'is a' justifies inheritance, and a sentence that uses 'has a' asks for a field instead.
Interview angles
What does `extends` actually give a class?+
The IS-A relationship plus the parent's inheritable members: fields, methods and nested types, all except constructors and inaccessible private members.
Inherited members live in the subclass object as if written there, and the type relationship means a subclass reference can stand anywhere the parent type is expected. Chains multiply: anything Manager gains from Employee also travels if someone later extends Manager.
class Employee { String name; } class Manager extends Employee { int teamSize; } Manager m = new Manager(); System.out.println(m.name); // inherited field
Common misconception: That inheritance copies code into the child class. The members are inherited through the relationship: change Employee once and every subclass follows immediately.
Follow-up: Can a class extend two parents?
Which members are not inherited?+
Constructors are never inherited, and private members cannot be accessed by the subclass, though they still exist inside every subclass object.
A constructor's job is tied to its own class, so the language refuses to pass it down; the child must offer its own or rely on the implicit default. private state can still influence behaviour through the parent's public methods, which is often the intended design.
class Employee { private int pin; // exists in every Manager object... int pin() { return pin; } // ...but only Employee code touches it directly } class Manager extends Employee { // int read() { return pin; } // error: pin has private access }
Common misconception: That private members disappear in subclasses. They are present in memory; the compiler just refuses direct access, which keeps the parent in charge of its own state.
Follow-up: How does a subclass reach private parent state safely?
What happens, in order, when a subclass object is created?+
Fields are defaulted, then constructors run from the top of the chain down: the parent's first (via super(...)), the child's last.
When the child's constructor begins, the parent's part is already complete. Writing super(...) as the first statement is required when you write it at all; omitting it inserts an implicit call to the parent's no-argument constructor, which fails to compile if the parent has none.
Manager(String name, int salary, int teamSize) { super(name, salary); // parent part first this.teamSize = teamSize; // then the child's own work }
Common misconception: That the child constructor runs first and calls upward only if it feels like it. The order is fixed: parents finish before children complete.
Follow-up: What does the compiler do when a parent has no no-argument constructor?
Why can a class have only one superclass?+
Single inheritance avoids the diamond ambiguity of one class inheriting conflicting state from two parents. Interfaces provide the many-types answer without the ambiguity.
If two parents could both contribute a field or constructor, which one builds it? Java closes that door: one state parent per class, unlimited type contracts through interfaces, which arrive in the Abstraction and Interfaces chapter.
class Manager extends Employee { } // one parent class Manager extends Employee, Boss { } // error: not legal Java
Common misconception: That Java is 'less powerful' for allowing one parent. State stays unambiguous, and interfaces cover the multi-type cases; the design is a trade, deliberately made.
Follow-up: How do interfaces provide multiple types without multiple state?
Is every class really an `Object`?+
Yes. A class with no extends extends Object implicitly, which is where toString, equals, hashCode and getClass come from.
That shared root is why every object can be printed, compared and reflected on. The default toString prints the class name plus a hash-style value, and default equals compares identity; real classes replace both, which the Object Contracts chapter takes apart.
System.out.println(m.getClass().getSimpleName()); // Manager // toString, equals, hashCode: inherited from Object unless overridden
Common misconception: That Object is an abstract concept with no methods. It is a real class with real defaults that every one of your classes silently carries.
Follow-up: What do the Object defaults do before a class overrides them?