Java中isinstance和instanceof的区别

2022/4/23 11:12:35

本文主要是介绍Java中isinstance和instanceof的区别,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

## 1. intanceof
---
```java
// 使用方法
if(a instanceof B);
// 表示object a是不是class B这种类型

2. isinstance


if(B.Class.isInstance(a));

// object a能否强制转换为class B这种类型

3.代码检验


// Java文件1
interface A{};

// Java文件2
class B{};

// Java文件3
public static void main(String[] args){
        class C implements A{};

        class D extends B{};
        C demo = new C();
        D demo2 = new D();
    
        // object instanceof class
        System.out.println(demo instanceof C); // true
        System.out.println("=======================");
    
        // object instanceof class of interface or parent class
        System.out.println(demo instanceof A); // true
        System.out.println(demo2 instanceof D); // true
        System.out.println(demo2 instanceof B); // true
        System.out.println("=======================");
    
        // object instance of class Object
        System.out.println(demo instanceof Object); // true
        System.out.println(demo2 instanceof Object); // true
        System.out.println("=======================");
    
        // object is null--> all false
        System.out.println(null instanceof Object); // false
        System.out.println("===========================");
    
        // class.isInstance(object)
        System.out.println(C.class.isInstance(demo)); // true
        System.out.println("===============================");
        
        // can object transfer to interface or parent class
        System.out.println(A.class.isInstance(demo)); // true
        System.out.println(B.class.isInstance(demo2)); // true
        System.out.println("========================");
    
        // can all object transfer to Object
        System.out.println(Object.class.isInstance(demo)); // true
        System.out.println(Object.class.isInstance(demo2)); // ture
        System.out.println("============================");

        // null object --> false
        System.out.println(Object.class.isInstance(null)); // false
    }


                   

这篇关于Java中isinstance和instanceof的区别的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程