a instanceof A:關(guān)鍵字的作用就是判斷類 A 的實(shí)例化對(duì)象能不能賦給對(duì)象 a,返回一個(gè) boolean 類型的數(shù)據(jù)。推薦好課:Java微課、Java進(jìn)階:Web開發(fā)實(shí)戰(zhàn)
舉例:
class A{
public void eat() {
System.out.println("父類A吃飯");
}
}
class B extends A{
public void eat() {
System.out.println("子類B吃飯");
}
}
class C extends A{
public void eat() {
System.out.println("子類C吃飯");
}
}
public class Shiyan {
public static void main(String[] args) {
// TODO Auto-generated method stub
A a=new B();//向上轉(zhuǎn)型,將類B的實(shí)例化賦給類A的對(duì)象
a.eat();//通過類A的對(duì)象去調(diào)用,類B的eat方法
// a instanceof A 關(guān)鍵字的作用就是判斷 類A的實(shí)例化對(duì)象能不能賦給對(duì)象a。
C c=(C)a;//使用強(qiáng)制轉(zhuǎn)換,將B類的實(shí)例化對(duì)象強(qiáng)制轉(zhuǎn)成C的實(shí)例化對(duì)象。編譯器可以編譯,但是運(yùn)行時(shí)會(huì)報(bào)轉(zhuǎn)換異常的錯(cuò)誤。
a.eat();
}
編譯器報(bào)了類型轉(zhuǎn)換異常
子類B吃飯
Exception in thread "main" java.lang.ClassCastException: class polymorphism.B cannot be cast to class polymorphism.C (polymorphism.B and polymorphism.C are in unnamed module of loader 'app')
at polymorphism.Shiyan.main(Shiyan.java:28)
改進(jìn)后使用關(guān)鍵字Instanceof代碼:
此時(shí)使用關(guān)鍵字Instanceof,判斷是否能轉(zhuǎn)換成功
class A{
public void eat() {
System.out.println("父類A吃飯");
}
}
class B extends A{
public void eat() {
System.out.println("子類B吃飯");
}
}
class C extends A{
public void eat() {
System.out.println("子類C吃飯");
}
}
public class Shiyan {
public static void main(String[] args) {
// TODO Auto-generated method stub
A a=new B();//向上轉(zhuǎn)型,將類B的實(shí)例化賦給類A的對(duì)象
a.eat();//通過類A的對(duì)象去調(diào)用,類B的eat方法
// a instanceof A 關(guān)鍵字的作用就是判斷 類A的實(shí)例化對(duì)象能不能賦給對(duì)象a。
boolean isturue=a instanceof C;
System.out.println(isturue);
}
子類B吃飯
false