在Java中,继承类和创建子类时,经常会遇到访问子类特定方法的问题来自超类内部。当您实例化子类对象并将其分配给超类变量时,就会发生这种情况。
要解决此限制,您可以使用以下方法之一:
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)
执行时通过强制转换,您可以暂时将该对象视为指定类型的实例。这允许您访问特定于子类的成员和方法。
考虑以下修改后的 Main 类:
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()); } }
在此示例中,Main 类成功检索使用石膏的狗的品种。
以上是在 Java 中如何从超类访问子类方法?的详细内容。更多信息请关注PHP中文网其他相关文章!