Home >Java >javaTutorial >How Can I Access Subclass Methods from a Superclass in Java?
In Java, when inheriting classes and creating subclasses, it's common to encounter issues accessing subclass-specific methods from within the superclass. This occurs when you instantiate a subclass object and assign it to a superclass variable.
To resolve this limitation, you can use either of the following methods:
Cat cat = new Cat("Feline", 12, "Orange"); cat.getName(); // OK cat.getColor(); // OK (getColor() is in Cat)
Pet pet = new Cat("Feline", 12, "Orange"); ((Cat)pet).getName(); // OK ((Cat)pet).getColor(); // OK (explicitly treated as Cat)
When you perform a cast, you temporarily treat the object as an instance of the specified type. This allows you to access subclass-specific members and methods.
Consider the following modified Main class:
public class Kennel { public static void main(String[] args) { // Create the pet objects Cat cat = new Cat("Feline", 12, "Orange"); Pet dog = new Dog("Spot", 14, "Dalmatian"); Pet bird = new Bird("Feathers", 56, 12); // Print out the status of the animals System.out.println("I have a cat named " + cat.getName() + ". He is " + cat.getAge() + " years old." + " He is " + cat.getColor() + ". When he speaks he says " + cat.speak()); // Using a cast to access a subclass-specific method ((Cat)dog).getBreed(); // dog is treated as Cat to access getBreed() System.out.println("I also have a dog named " + dog.getName() + ". He is " + dog.getAge() + " years old." + " He is a " + ((Cat)dog).getBreed() + ". When he speaks he says " + dog.speak()); System.out.println("And Finally I have a bird named " + bird.getName() + ". He is " + bird.getAge() + " years old." + " He has a wingspan of " + bird.getWingspan() + " inches." + " When he speaks he says " + bird.speak()); } }
In this example, the Main class successfully retrieves the breed of the dog using a cast.
The above is the detailed content of How Can I Access Subclass Methods from a Superclass in Java?. For more information, please follow other related articles on the PHP Chinese website!