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

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

Linda Hamilton
Linda HamiltonOriginal
2024-12-21 03:20:10199browse

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());
    }
}

The above is the detailed content of How Can I Access Subclass Methods from a Superclass Variable in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn