Module 3 of 6 · Java OOP Fundamentals · Beginner

Inheritance: Code Reuse

Duration: 5 min

What is Inheritance?

Inheritance is a mechanism where a new class (subclass or child class) inherits properties and methods from an existing class (superclass or parent class). This promotes code reuse and establishes a hierarchical relationship between classes.

Inheritance follows an 'is-a' relationship. For example, a Dog 'is-a' Animal.

Creating a Superclass

public class Animal {
    protected String name;
    protected int age;
    
    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public void eat() {
        System.out.println(name + " is eating.");
    }
    
    public void sleep() {
        System.out.println(name + " is sleeping.");
    }
    
    public void displayInfo() {
        System.out.println("Name: " + name + ", Age: " + age);
    }
}
No output - this is a class definition

Creating a Subclass

public class Dog extends Animal {
    private String breed;
    
    public Dog(String name, int age, String breed) {
        super(name, age);  // Call parent constructor
        this.breed = breed;
    }
    
    // Override method from parent class
    @Override
    public void eat() {
        System.out.println(name + " is eating dog food.");
    }
    
    // New method specific to Dog
    public void bark() {
        System.out.println(name + " says: Woof! Woof!");
    }
    
    @Override
    public void displayInfo() {
        super.displayInfo();  // Call parent method
        System.out.println("Breed: " + breed);
    }
}
No output - this is a class definition
public class InheritanceDemo {
    public static void main(String[] args) {
        Dog dog = new Dog("Buddy", 5, "Golden Retriever");
        
        dog.displayInfo();
        dog.eat();
        dog.sleep();
        dog.bark();
    }
}
Name: Buddy, Age: 5
Breed: Golden Retriever
Buddy is eating dog food.
Buddy is sleeping.
Buddy says: Woof! Woof!

The super Keyword

The 'super' keyword is used to refer to the parent class. It's used to:
• Call the parent class constructor
• Call parent class methods
• Access parent class variables

Method Overriding

Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in the parent class. The @Override annotation is used to indicate that a method is overriding a parent method.

💡 Tip: Use the @Override annotation when overriding methods. This helps catch errors if the method signature doesn't match the parent class.

Learn more: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

❓ What keyword is used to inherit from a parent class?

❓ What is a best practice when working with Inheritance?

💡 Tip: Pro Tip: Master Inheritance thoroughly. This foundation is crucial for writing professional Java code.

← Previous Continue interactively → Next →

Related Courses