ITKokka
Lesson 1 ยท Note 6

Inheritance

๐Ÿ“Œ The Short Note

Download

๐Ÿ“– Explanation

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 โ†’ PartTimeEmployee

A 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 Example
class 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 extends keyword.
  • 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 extends to 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.
Share:
โ† AbstractionPolymorphism โ†’