What Is Inheritance? The extends Keyword
What you'll learn: How to create specialized classes that inherit properties and behaviors from more general classes using the extends keyword.
The Core Idea
Inheritance models an "is-a" relationship between classes. When one class is a specialized type of another, you can use inheritance to reuse and extend the parent class's code.
Think of it like biological inheritance: a Golden Retriever is a Dog, and a Dog is a Animal. Each level inherits traits from the level above while adding its own specific characteristics. In Java, the more general class is called the superclass (or parent class), and the specialized class is called the subclass (or child class).
The extends Keyword
To create a subclass, use the extends keyword:
public class Animal {
private String name;
public void eat() {
System.out.println("Animal is eating");
}
}
public class Dog extends Animal {
// Dog inherits name field and eat() method from Animal
public void bark() {
System.out.println("Woof!");
}
}
Now Dog automatically has access to everything public or protected in Animal, plus its own unique bark() method. A Dog object can call both eat() (inherited) and bark() (its own).
Why Use Inheritance?
- Code reuse: Write common behavior once in the superclass
- Logical organization: Model real-world relationships
- Extensibility: Add specialized behavior without modifying the original class
Key Takeaway: Inheritance uses the extends keyword to create subclasses that inherit fields and methods from a superclass, modeling "is-a" relationships and enabling code reuse through specialization.