OOP Pillar: Inheritance (extends keyword) - Java Cource

Learn Java inheritance using extends keyword with examples. Understand subclass, superclass, and multi-level inheritance.
OOP Pillar: Inheritance (extends keyword)

On Day 23, we learn about inheritance in Java. Inheritance allows a class (called the subclass or child class) to acquire the fields and methods of another class (called the superclass or parent class). This is done using the extends keyword.

1. Basic Inheritance


class Person {
    String name;
    int age;

    void displayInfo() {
        System.out.println(name + " is " + age + " years old.");
    }
}

// Student inherits from Person
class Student extends Person {
    String course;

    void study() {
        System.out.println(name + " is studying " + course);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student();
        s.name = "Alice"; // inherited field
        s.age = 20;       // inherited field
        s.course = "Java"; // own field

        s.displayInfo(); // inherited method
        s.study();       // subclass method
    }
}

Explanation: Student automatically gets the fields and methods of Person. We don’t need to rewrite them.

2. Multi-level Inheritance


class Person {
    String name;
}

class Student extends Person {
    int rollNumber;
}

class GraduateStudent extends Student {
    String thesisTopic;
}

public class Main {
    public static void main(String[] args) {
        GraduateStudent g = new GraduateStudent();
        g.name = "Bob";        // from Person
        g.rollNumber = 101;    // from Student
        g.thesisTopic = "AI";  // from GraduateStudent

        System.out.println(g.name + " (Roll: " + g.rollNumber + ") Thesis: " + g.thesisTopic);
    }
}

Explanation: GraduateStudent inherits from Student, which in turn inherits from Person. This is multi-level inheritance.

3. Why Use Inheritance?

  • Reusability – avoid duplicating code.
  • Readability – organize classes into a hierarchy.
  • Extensibility – easily add new functionality in subclasses.

Summary

The extends keyword in Java enables a class to inherit fields and methods from another class. Inheritance improves code reusability and creates a logical class hierarchy.

Post a Comment