Course contentsShow
← Java
Lesson 396 of 2,87010. Inheritance FundamentalsFree lesson

Inheriting Fields from a Superclass

See how subclasses automatically gain all non-private fields from their superclass.

Inheriting Fields from a Superclass

What you'll learn: How subclasses automatically receive all non-private fields from their parent class.

When you create a subclass using the extends keyword, something powerful happens behind the scenes: your new class automatically gains access to all of its superclass's fields—except for private ones.

Understanding Field Inheritance

Think of inheritance like receiving a family heirloom. When a child class extends a parent class, it inherits the parent's characteristics. If the parent has public, protected, or package-private fields, the child can use them as if they were declared directly in the child class itself.

However, private fields are like personal secrets—they remain hidden in the superclass and cannot be directly accessed by the subclass, even though they technically exist in memory when the subclass object is created.

A Simple Example

class Animal {
    public String name;
    protected int age;
    String species;  // package-private
    private double weight;
}

class Dog extends Animal {
    public void showInfo() {
        System.out.println(name);     // ✓ Inherited and accessible
        System.out.println(age);      // ✓ Inherited and accessible
        System.out.println(species);  // ✓ Inherited and accessible
        // System.out.println(weight); // ✗ Compile error: private!
    }
}

When you create a Dog object, it has name, age, and species fields available for direct use. The weight field exists in memory but is only accessible through Animal's methods (if any exist).

Why This Matters

Field inheritance eliminates code duplication. Common attributes live in the superclass, while subclasses focus on their specialized features.

Key Takeaway: Subclasses automatically inherit all non-private fields from their superclass and can use them directly based on their access level—private fields exist but remain inaccessible to the subclass.