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
Release: 2024-12-21 03:20:10
Original
136 people have browsed it

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
    }
}
Copy after login

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
Copy after login

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
Copy after login

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template