"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Access Subclass Methods from a Superclass Variable in Java?

How Can I Access Subclass Methods from a Superclass Variable in Java?

Posted on 2025-03-24
Browse:683

How Can I Access Subclass Methods from a Superclass Variable in Java?

Accessing Subclass Methods from Superclass

In object-oriented programming, inheritance allows classes to inherit properties and behaviors from their parent classes. However, when accessing methods of subclasses from a superclass variable, some limitations occur.

Consider the following code snippet:

abstract public class Pet {
    ...
}

public class Cat extends Pet {
    private String color;
    public String getColor() { ... }
}

public class Kennel {
    public static void main(String[] args) {
        Pet cat = new Cat("Feline", 12, "Orange");
        cat.getColor(); // Compiler error: getColor() not defined in Pet
    }
}

In the Kennel class, when a Cat object is assigned to a Pet variable, only members defined in Pet are accessible. This includes methods like getName() and getAge(), but not getColor().

To resolve this, there are two options:

1. Declare Variable as Subclass:

Declare the variable as the specific subclass:

Cat cat = new Cat("Feline", 12, "Orange");
cat.getColor(); // Valid, getColor() is defined in Cat

2. Cast Variable to Subclass:

Cast the variable to a known or expected subclass:

Pet cat = new Cat("Feline", 12, "Orange");
((Cat)cat).getColor(); // Valid, getColor() is accessible via casting

Example Implementation:

Here is a corrected version of the Kennel class:

public class Kennel {
    public static void main(String[] args) {
        Cat cat = new Cat("Feline", 12, "Orange");
        System.out.println("Cat's color: "   cat.getColor());
    }
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3