Concept · Intro

Inheritance

A subclass IS-A superclass — it inherits the parent’s fields and methods for free, and may add to or override them.

Asked atAmazonMicrosoftOracle
step 1 / 9
1/2A family tree
is-ais-ais-a
Vehicle
# speed: int
+ start()
+ stop()
Car
+ openTrunk()
Motorcycle
+ start()
Truck
+ load()
A family tree
1class Vehicle {
2 protected int speed;
3 void start() { ... }
4 void stop() { ... }
5}
6 
7class Car extends Vehicle { void openTrunk(){...} }
8class Truck extends Vehicle { void load(){...} }
9class Motorcycle extends Vehicle { void start(){...} } // override
State
# protectedshared with children

The base class holds what every vehicle shares: a protected speed field (#) and the start()/stop() operations. Define it once, here.