• instanceof用法及本质:


    import static java.lang.System.*;
    public class InstanceofTest{
    	public static void main(String[] args){
    		//-引用变量hello的编译类型为Object,实际类型为String,Object类为所有类的父类
    		Object hello="hello";
    		//-String 与Object存在继承关系,可以进行 instanceof 计算,返回true
    		out.println(hello instanceof Object);
    		//-hello实际类型为String,可以进行 instanceof 计算,返回true
    		out.println(hello instanceof String);
    		//-Math与Object存在继承关系,可以进行 instanceof 计算
    		//-但hello实际类型为String,与Math不存在继承关系,不能转换,所以返回false
    		out.println(hello instanceof Math);
    		//-String类型实现了Comparable接口,可以进行 instanceof 计算,返回true
    		out.println(hello instanceof Comparable);
    
    		//-a为彻头彻尾的String 类型,与Math不存在继承关系,不可以进行 instanceof 计算,编译就不会通过,会报错
    		String a="hello";
    		//out.println(a instanceof Math);
    	}
    }
    

    运行结果:

    总结:

    1、用于判断前面的对象是否是后面的类,或者其子类、实现类的实例,是,返回true,不是,返回false

    2、前面对象的编译时类型,要么与后面 的类相同,要么与后面的类具有父子继承关系,否则会引起编译错误

  • 相关阅读:
    find 以及linux 和windows 文件互传
    27 关于Object类 -- equals()
    26 super关键字
    25 访问修饰符限定词
    24 继承 子类中方法重写
    23 static 关键字
    22 包(package)来解决不同包下同名文件的冲突问题
    21 封装(get,set方法)
    20 带参构造方法(this关键字)
    19 无参构造方法
  • 原文地址:https://www.cnblogs.com/baby-zhude/p/8040362.html
Copyright © 2020-2023  润新知