Understanding Java Inheritance

Textual Information

Inheritance in Java allows one class to inherit the fields and methods of another class. It promotes code reusability and establishes a relationship between classes. The class that inherits is called the subclass, while the class being inherited from is called the superclass.


Click to learn more

Video Information

Code Snippets

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

class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat(); // Inherited method
        dog.bark(); // Dog's own method
    }
}
                        

Quiz

Test your knowledge on Java inheritance:

1. What does inheritance allow a class to do in Java?

2. Which keyword is used to inherit a class in Java?

3. What can a subclass do in Java?