在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中文網其他相關文章!