You are on page 1of 5

Inheritance

• A way of organizing classes


• Term comes from inheritance of traits like eye
color, hair color, and so on.
• Classes with properties in common can be
grouped so that their common properties are
only defined once.
An Inheritance Hierarchy
Vehicle

Automobile Motorcycle Bus

Sedan Sports Car School Bus Luxury Bus

What properties does each vehicle inherit from the


types of vehicles above it in the diagram?
Inheritance
• A class can extend another class, inheriting all
its data members and methods while redefining
some of them and/or adding its own.
Objects inherit from their
superclasses
• A class describes fields and methods
• Objects of that class have those fields and
methods
• But an object also inherits:
• the fields described in the class's superclasses

• the methods described in the class's

superclasses
• A class is not a complete description of its objects!
Example of inheritance
class Person { class Employee
String name; extends Person {
String age; double salary;
void birthday () { void pay () { ...}
age = age + 1; }
}
}

Every Employee has a name, age, and birthday method


as well as a salary and a pay method.

You might also like