Skip to main content
Course/Module 5/Topic 1 of 3Intermediate

inheritance Basics

inheritance allows a class to inherit fields and methods from another class. The child class (subclass) extends the parent class (superclass), promoting code reuse and creating a natural hierarchy.

40 minBy Priygop TeamLast updated: Feb 2026

Understanding inheritance

inheritance creates an 'is-a' relationship. A Dog 'is-a' Animal, a Car 'is-a' Vehicle. The child class inherits all public and protected members from the parent and can add new ones or override existing behavior. Java uses the 'extends' keyword for inheritance.

inheritance in Action

Example
// Parent class (superclass)
class Animal {
    String name;
    int age;
    
    Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    void eat() {
        System.out.println(name + " is eating.");
    }
    
    void sleep() {
        System.out.println(name + " is sleeping.");
    }
    
    void info() {
        System.out.println(name + " (Age: " + age + ")");
    }
}

// Child class — inherits Animal's fields & methods
class Dog extends Animal {
    String breed;
    
    Dog(String name, int age, String breed) {
        super(name, age);  // Call parent constructor
        this.breed = breed;
    }
    
    void bark() {
        System.out.println(name + " says: Woof!");
    }
    
    void fetch(String item) {
        System.out.println(name + " fetches the " + item + "!");
    }
}

class Cat extends Animal {
    boolean isIndoor;
    
    Cat(String name, int age, boolean isIndoor) {
        super(name, age);
        this.isIndoor = isIndoor;
    }
    
    void purr() {
        System.out.println(name + " is purring...");
    }
}

public class InheritanceDemo {
    public static void main(String[] args) {
        Dog dog = new Dog("Buddy", 3, "Labrador");
        Cat cat = new Cat("Whiskers", 5, true);
        
        // Inherited methods
        dog.info();
        dog.eat();
        dog.bark();     // Dog-specific
        dog.fetch("ball");
        
        System.out.println();
        cat.info();
        cat.sleep();
        cat.purr();     // Cat-specific
    }
}

Try It Yourself: Vehicle Hierarchy

Try It Yourself: Vehicle HierarchyJava
Java Editor
✓ ValidTab = 2 spaces
Java|63 lines|1392 chars|✓ Valid syntax
UTF-8

Quick Quiz: inheritance

Chat on WhatsApp
Priygop - Leading Professional Development Platform | Expert Courses & Interview Prep