ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

instanceof 关键字

instanceof 关键字 一、instanceof 是什么instanceof是 Java二元关键字不是方法。作用判断对象实际实例类型判断该引用变量指向的真实对象是否属于某个类、子类、实现类。返回值布尔类型true/false核心用途向下转型前做安全校验避免运行时ClassCastException类型转换异常语法格式对象引用变量 instanceof 类名⚠重点判断看的是new出来的真实对象不是等号左边引用的类型。二、基础代码演示class Animal{} class Dog extends Animal{} class Cat extends Animal{} public class InstanceofBasicDemo { public static void main(String[] args) { //向上转型父类引用指向Dog对象 Animal a1 new Dog(); System.out.println(a1 instanceof Dog); //true真实对象是Dog System.out.println(a1 instanceof Animal); //trueDog是Animal子类 System.out.println(a1 instanceof Cat); //false真实对象不是Cat Animal a2 new Cat(); System.out.println(a2 instanceof Dog); //false } }输出结果true true false false三、标准开发使用模板向下转型搭配 instanceof开发规范只要做向下强制类型转换必须先用 instanceof 判断。class Animal{} class Dog extends Animal{ //子类独有方法 public void watchHouse(){ System.out.println(小狗看家护院); } } class Cat extends Animal{ //子类独有方法 public void catchMouse(){ System.out.println(小猫抓老鼠); } } public class SafeCastDemo { //接收父类类型参数可以传入任意子类对象 public static void doSomething(Animal animal){ //判断真实对象是不是Dog if(animal instanceof Dog){ //安全之后向下强制转型 Dog dog (Dog) animal; dog.watchHouse(); }else if(animal instanceof Cat){ Cat cat (Cat) animal; cat.catchMouse(); }else{ System.out.println(未知动物); } } public static void main(String[] args) { doSomething(new Dog()); doSomething(new Cat()); } }输出小狗看家护院 小猫抓老鼠如果不加 instanceof 判断的报错示范Animal animal new Cat(); Dog dog (Dog) animal; //编译完全不报错运行抛出 ClassCastException编译期只检查父子继承关系不会检查运行时真实对象错误只有运行才暴露非常隐蔽。四、null 与 instanceof如果引用变量是nullnull instanceof 任意类结果永远返回 false不会空指针异常。Animal an null; System.out.println(an instanceof Dog); //输出 false五、Java14 instanceof 模式匹配了解初学者可以先不写简化写法判断成功的同时直接生成子类变量不用手动强转。public static void test(Animal animal){ //模式匹配如果animal是Dog直接定义dog变量 if(animal instanceof Dog dog){ dog.watchHouse(); //直接使用dog不需要写(Dog)animal强转 } }六、常见易错点总结instanceof判断真实 new 出来的对象不是左边的引用类型。Animal a new Dog(); //a是Animal引用但是new的是Dog所以 a instanceof Dog → true两个类没有继承 / 实现关系使用 instanceof 直接编译报错。null instanceof 任何类→ false不会抛空指针。只用来做引用类型对象判断不能用于基本数据类型int、double 等。向下转型固定流程if(对象 instanceof 子类){ 强制转型调用子类特有方法 }。七、本章小结instanceof返回布尔值检测对象真实类型主要目的规避向下转型的ClassCastException运行异常null 参与运算返回 false无继承关系直接编译报错Java14 模式匹配可以简化代码初学优先掌握传统写法。
返回列表