Course contentsShow
← Java
Lesson 441 of 2,87011. Polymorphism and Dynamic DispatchFree lesson

Method Availability After Upcasting

Understanding that only superclass methods are accessible through an upcast reference.

Method Availability After Upcasting

What you'll learn: You'll understand why you can only call superclass methods through an upcast reference, even though the object itself might have more capabilities.

The Core Idea

When you upcast an object to a superclass reference, you lose access to any methods that were added in the subclass. The reference type determines which methods you can call, not the actual object type. It's like viewing the object through a filter that only shows the superclass's methods.

Why This Happens

Java uses the reference type to determine what methods are available at compile time. If you have an Animal reference (even though it points to a Dog object), the compiler only knows about methods declared in Animal. Any Dog-specific methods become invisible through that reference.

Analogy

Think of it like a universal TV remote (superclass) controlling a smart TV (subclass). The smart TV can stream Netflix, but if you're using the basic universal remote, you only have access to the standard buttons: power, volume, and channel. The streaming features are still there in the TV, but your remote doesn't have buttons to access them.

Example

class Animal {
    public void eat() {
        System.out.println("Animal eating");
    }
}

class Dog extends Animal {
    public void bark() {
        System.out.println("Woof!");
    }
}

// Upcasting
Animal myAnimal = new Dog();
myAnimal.eat();   // ✓ Works - eat() is in Animal
myAnimal.bark();  // ✗ Compilation error - bark() not visible through Animal reference

Key Takeaway: After upcasting, only the superclass methods are accessible through the reference, even though the actual object has more methods available—the reference type acts as a "visibility window" limiting what you can call.