Back to course

OOP Pillar 2: Inheritance Basics (extends keyword)

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 20: OOP Pillar 2: Inheritance Basics

Inheritance is a mechanism in which one class acquires the properties and behaviors (fields and methods) of another class. It promotes code reusability and establishes an 'is-a' relationship (e.g., A Dog is a Mammal).

Terminology

  • Parent Class (Superclass): The class being inherited from.
  • Child Class (Subclass): The class that inherits from the parent.

Implementing Inheritance (extends)

In Java, a child class uses the extends keyword to inherit from a parent class. Java supports only single inheritance (a class can extend only one other class).

java // Superclass public class Animal { public void eat() { System.out.println("This animal eats food."); }

public void sleep() {
    System.out.println("The animal is sleeping.");
}

}

// Subclass inherits properties and methods from Animal public class Dog extends Animal { public void bark() { System.out.println("Dog barks."); } }

Benefits of Inheritance

  1. Code Reusability: Methods written in the parent class (like eat() and sleep()) do not need to be rewritten in the child class (Dog).
  2. Polymorphism: A Dog object can be treated as an Animal object (covered later).

Usage

java Dog myDog = new Dog(); myDog.bark(); // Defined in Dog myDog.eat(); // Inherited from Animal myDog.sleep(); // Inherited from Animal

Important: Constructors, private members, and static members are generally not inherited in the traditional sense. Private fields exist in the subclass, but they cannot be accessed directly.