Inheritance
Inheritance is a way to create a relationship between classes so a Child class can reuse the attributes and methods of a Parent class.
- Parent class: holds common features.
- Child class: shares the parent's features, and adds its own.
Real World Example: Employee
Example: Employee โ PartTimeEmployeeA PartTimeEmployee is also an Employee. This is called an "is a" relationship.
- PartTimeEmployee is an Employee.
- Both share common things:
name,email,work(). - PartTimeEmployee also has its own feature:
workingHours.
Inheritance in Java
Code Exampleclass Employee {
String name;
String email;
public void work() {
System.out.println("Working...");
}
}
class PartTimeEmployee extends Employee {
int workingHours;
}
extends is the keyword used to inherit a class in Java. PartTimeEmployee automatically gets name, email, and work() from Employee, without rewriting them, and still defines its own workingHours.
Class Diagram
โโโโโโโโโโโโโโโโโโโโโโโโโ
โ Employee โ
โโโโโโโโโโโโโโโโโโโโโโโโโค
โ name โ
โ email โ
โ work() โ
โโโโโโโโโโโโโโโโโโโโโโโโโ
โฒ
โ extends
โโโโโโโโโโโโโโโโโโโโโโโโโ
โ PartTimeEmployee โ
โโโโโโโโโโโโโโโโโโโโโโโโโค
โ workingHours โ
โโโโโโโโโโโโโโโโโโโโโโโโโ
The arrow points from the child class up to the parent class it extends. PartTimeEmployee inherits everything Employee has, and adds workingHours on top.
Key Idea: Inheritance = "is a" relationship + sharing common features. PartTimeEmployee is an Employee.
Exam Focus Points
- Inheritance lets a child class reuse a parent class's attributes and methods through the
extendskeyword. - The relationship between parent and child is described as "is a": PartTimeEmployee is an Employee.
- A child class can still add its own extra attributes or methods on top of what it inherits.
Summary
- Inheritance creates a parent and child relationship between classes so common features can be shared.
- The child class uses
extendsto inherit the parent's attributes and methods without rewriting them. - The child class can still define its own additional attributes and methods.
- Inheritance = "is a" relationship + sharing common features.