Adding New Fields and Methods in Subclasses
What You'll Learn
You'll learn how subclasses can expand their parent's functionality by declaring their own unique fields and methods beyond what they inherit.
The Core Idea
When a class inherits from a superclass using extends, it automatically gets all the accessible fields and methods from its parent. But inheritance isn't just about reusing what already exists—it's also about extending that functionality. A subclass can declare its own additional fields and methods that the superclass doesn't have.
Think of it like generations in a family: a child inherits traits from their parents (eye color, height genes), but also develops their own unique characteristics (a talent for music, a love of photography). Similarly, a subclass inherits from its parent but can add brand-new capabilities.
How It Works
When you declare a subclass, you can add:
- New fields that store additional state specific to the subclass
- New methods that provide behaviors the superclass doesn't offer
These additions don't affect the superclass at all—they only exist in the subclass and its instances.
public class Vehicle {
private int speed;
public void accelerate() {
speed += 10;
}
}
public class Car extends Vehicle {
private int numberOfDoors; // New field
private String licensePlate; // Another new field
public void honkHorn() { // New method
System.out.println("Beep beep!");
}
}
A Car object has everything a Vehicle has (speed and accelerate()), plus its own additions (numberOfDoors, licensePlate, and honkHorn()).
Why This Matters
This ability to extend functionality is what makes inheritance powerful for modeling specialized types. You build upon existing, tested code while adding exactly what makes the subclass unique.
Key Takeaway: Subclasses inherit their parent's accessible members and can declare additional fields and methods to provide specialized functionality beyond what the superclass offers.