在Java中,向上轉型和向下轉型是用來處理父類與子類之間的關系的。
class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("Dog is eating");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog(); // 向上轉型
animal.eat(); // 輸出 Dog is eating
}
}
class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("Dog is eating");
}
public void bark() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog(); // 向上轉型
if (animal instanceof Dog) {
Dog dog = (Dog) animal; // 向下轉型
dog.bark(); // 輸出 Dog is barking
}
}
}
需要注意的是,向下轉型時一定要進行類型檢查,以避免出現ClassCastException異常。