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

Type Compatibility: Subclass Instances as Superclass References

Understand that a subclass instance can be assigned to a superclass reference due to the is-a relationship.

Type Compatibility: Subclass Instances as Superclass References

You'll learn: How Java allows you to treat a subclass object as if it were its superclass type, thanks to the "is-a" relationship.

The Core Idea

When you create a subclass using extends, you establish an is-a relationship. A Dog is an Animal, a Car is a Vehicle. Because of this relationship, Java allows you to assign a subclass instance to a superclass reference variable. This is called type compatibility or substitutability.

Think of it like this: if you need someone who can "speak Spanish," any person who can "speak multiple languages including Spanish" qualifies. The more specific person (multilingual) can substitute for the more general requirement (Spanish speaker).

How It Works

When you declare a reference variable with a superclass type, it can hold any instance of that superclass or any of its subclasses:

class Animal {
    String name;
}

class Dog extends Animal {
    String breed;
}

// This works because Dog IS-AN Animal
Animal myAnimal = new Dog();

Here, myAnimal is a reference of type Animal, but it's pointing to a Dog object in memory. This is perfectly legal because every Dog is guaranteed to have all the features of an Animal (it inherited them).

Why This Matters

Type compatibility is foundational for writing flexible code. You can write methods that accept superclass parameters and work with any subclass:

public void printAnimalName(Animal a) {
    // Works with Dog, Cat, Bird, etc.
}

Key Takeaway: A subclass instance can be assigned to a superclass reference because the is-a relationship guarantees the subclass has all inherited members of the superclass, making them type-compatible.