instanceof
instanceof 是java的一个保留关键字
使用方法
object instanceof Class | Interface
返回值类型: boolean
true :代表左边对象是右边的 类\接口 或者其 子类\接口 的 实例化对象\实现类
使用场景
存在继承关系的类或者接口之间
向下进行转型的判断
注意事项(以类为例子,接口和类一样)
在编译阶段的时候:
如果object是Class 的实例、子类或者父类均可以通过编译
运行阶段:
object是Class的实例或者子类的时候,返回值为true,为Class的父类时,返回值为false
举个例子:所有的猫咪都是动物,但是不能说所有的动物都是猫咪
栗子
package com.blog.instanceoftest;
import com.sun.org.apache.bcel.internal.generic.FADD;
/**
* @Author jinhuan
* @Date 2022/3/23 16:47
* Description:
*/
public class Test01 {
public static void main(String[] args) {
Father father = new Father();
System.out.println(father instanceof SuperFather);
System.out.println(father instanceof Father);
System.out.println(father instanceof Comparable);
System.out.println(father instanceof Son);
}
}
/*
定义一"族" 类
*/
class SuperFather{}
class Father extends SuperFather implements Comparable{
@Override
public int compareTo(Object o) {
return 0;
}
}
class Son extends Father{}
package com.blog.instanceoftest;
/**
* @Author jinhuan
* @Date 2022/3/23 16:57
* Description:
*/
public class Test02 {
public static void main(String[] args) {
FatherImpl father = new FatherImpl();
System.out.println(father instanceof SuperFather);
System.out.println(father instanceof Father);
System.out.println(father instanceof Son);
}
}
/*
定义一"族" 接口
*/
interface SuperFather{}
interface Father extends SuperFather {}
interface Son extends Father{}
class FatherImpl implements Father{
}
以上均为本人个人观点,借此分享。如有不慎之处,劳请各位批评指正!鄙人将不胜感激并在第一时间进行修改!
传送门:😄
java基础之多态