向上轉型:符合“is a”,是安全的,子類向上到父類,多餘的屬性和方法會丟棄
向下轉型:不安全的,用instanceof提前判斷一下,以免丟擲異常
instanceof用法:
result = object instanceof class
result:布林型別
object:必選項,任意物件表示式
class:必選項,任意已定義的物件類
說明: 如果object是class或者其子類的一個例項,則instanceof運算子返回true,如果不是或者object是null,則返回false
public class AnimalDemo { public static void main(String[] args) { // TODO Auto-generated method stub Animal animal1 = new Dog("旺財");//向上轉型 Animal animal2 = new Cat("招財貓"); animal1.eat(); //animal1.sleep();因為向上轉型,所以子類的sleep()丟棄了 //父類的引用變數只能呼叫父類中有的方法,或者是子類重寫父類的方法 animal2.eat(); //向下轉型不安全,需要提前用instanceof判斷一下,防止異常丟擲 if(animal2 instanceof Cat){ System.out.println("111"); Cat cat = (Cat)animal2; cat.sleep(); } } } class Animal{ private String name; public Animal(String name) { this.name = name; } public void eat() {//子類要重寫 System.out.println(name); } } class Dog extends Animal{ public Dog(String name) { super(name); } public void eat() { System.out.println("吃狗糧"); } public void sleep() { System.out.println("sleep"); } } class Cat extends Animal{ public Cat(String name) { super(name); } public void eat() { System.out.println("吃貓糧"); } public void sleep() { System.out.println("sleep"); } }