Animal.java:
package com.imooc.animal;public class Animal { private String name; private int month; public Animal(){ } public Animal(String name,int month){ this.setName(name); this.setMonth(month); } //eat() public void eat(){ System.out.println("動物都又吃東西的能力。"); } //getter/setterpublic String getName() {return name;}public void setName(String name) {this.name = name;}public int getMonth() {return month;}public void setMonth(int month) {this.month = month;} }
Cat.java:
package com.imooc.animal;public class Cat extends Animal { private String name;private int month;private double weight;public Cat(){}public Cat(String name,int month,double weight){super(name,month);//super父類屬性構造方法賦值setWeight(weight);}//runpublic void run(){System.out.println("貓會跑");}//方法重寫@Overridepublic void eat() {System.out.println("貓吃魚。");}//getter/setterpublic String getName() {return name;}public void setName(String name) {this.name = name;}public int getMonth() {return month;}public void setMonth(int month) {this.month = month;}public double getWeight() {return weight;}public void setWeight(double weight) {this.weight = weight;}}
test.java:
package com.imooc.test;import com.imooc.animal.Animal;import com.imooc.animal.Cat;import com.imooc.animal.Dog;public class test {public static void main(String[] args) {Animal one=new Animal();//1普通建立執行個體one.eat();Animal two=new Cat();//2.向上轉型two.eat();System.out.println("=====================");/* * 向下轉型(強制轉型) * 子類引用指向父類的執行個體(對象),此處必須今習慣強制類型轉換 * 該執行個體可以調用子類特有的方法 * 必須滿足轉型條件才能轉換() */Cat temp=(Cat)two;//3.向下轉型,原本two是Animal類型,強制類型轉換為Cattemp.eat();temp.run();temp.setMonth(3);System.out.println("年齡:"+temp.getMonth());/* Dog temp2=(Dog)two;temp2.eat();temp2.sleep();temp2.getSex();以上的操作雖然系統不會報錯,但是運行拋出異常,原因:two在建立時究其根本是指向Cat(),所以上面類縮小到cat可以但是轉成dog就不行*/}}
執行情況
:
為解決上面問題:
引入instanceof 關鍵字:instanceof是Java、php的一個二元操作符(運算子),和==,>,<是同一類東西。由於它是由字母組成的,所以也是Java的保留關鍵字。它的作用是判斷其左邊對象是否為其右邊類的執行個體,返回boolean類型的資料。可以用來判斷繼承中的子類的執行個體是否為父類的實現。
instanceof一般放在類型轉換的前面,合理規避異常產生。
package com.imooc.test;import com.imooc.animal.Animal;import com.imooc.animal.Cat;import com.imooc.animal.Dog;public class test {public static void main(String[] args) {Animal one=new Animal();//1普通建立執行個體one.eat();Animal two=new Cat();//2.向上轉型two.eat();System.out.println("=====================");/* * 向下轉型(強制轉型) * 子類引用指向父類的執行個體(對象),此處必須今習慣強制類型轉換 * 該執行個體可以調用子類特有的方法 * 必須滿足轉型條件才能轉換(),子類間不能隨意強制轉換,但是子類引用指向父類執行個體,可以強制轉換 * instanceof運算子:返回true/false, */if(two instanceof Cat){Cat temp=(Cat)two;//3.向下轉型,原本two是Animal類型,強制類型轉換為Cattemp.eat();temp.run();temp.setMonth(3);System.out.println("two可以轉換為Cat類型");}if(two instanceof Dog){Dog temp2=(Dog)two;temp2.eat();temp2.sleep();temp2.getSex();System.out.println("two可以轉換為Dog類型");}if(two instanceof Animal){System.out.println("two可以轉換為Animal類型");}if(two instanceof Object){System.out.println("two可以轉換為Object類型");}}}
執行情況: