Instanceof and isinstance in Java
•
Java
public class Main {
public static void main(String[] args) {
C t1=new C();
D t2=new D();
//obj instanceof class:这个对象是不是这种类型.
//测试1:一个对象是本身类的一个对象
System.out.println(t1 instanceof C);
//测试2:一个对象是本身类父类(父类的父类)和接口的一个对象
System.out.println(t1 instanceof A);
System.out.println(t2 instanceof D);
//测试3:所有对象都是object
System.out.println(t1 instanceof Object);
System.out.println(t2 instanceof Object);
//测试4:凡是null相关的都是false
System.out.println(null instanceof Object);
System.out.println(null instanceof B);//class.<a href="https://www.jb51.cc/tag/isinstance/" target="_blank" class="keywords">isinstance</a>(obj):这个对象能不能被转化为这个类 //测试1:<a href="https://www.jb51.cc/tag/yige/" target="_blank" class="keywords">一个</a>对象是本身类的<a href="https://www.jb51.cc/tag/yige/" target="_blank" class="keywords">一个</a>实例 Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println(C.class.<a href="https://www.jb51.cc/tag/isinstance/" target="_blank" class="keywords">isinstance</a>(t1)); //测试2:<a href="https://www.jb51.cc/tag/yige/" target="_blank" class="keywords">一个</a>对象能被转化为本身类所继承的类(<a href="https://www.jb51.cc/tag/fulei/" target="_blank" class="keywords">父类</a>的<a href="https://www.jb51.cc/tag/fulei/" target="_blank" class="keywords">父类</a>)和实现的接口(接口的父接口)强转 Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println(A.class.<a href="https://www.jb51.cc/tag/isinstance/" target="_blank" class="keywords">isinstance</a>(t1)); Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println(B.class.<a href="https://www.jb51.cc/tag/isinstance/" target="_blank" class="keywords">isinstance</a>(t2)); //测试3:所有对象都能被Object强转 Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println(Object.class.<a href="https://www.jb51.cc/tag/isinstance/" target="_blank" class="keywords">isinstance</a>(t1)); Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println(Object.class.<a href="https://www.jb51.cc/tag/isinstance/" target="_blank" class="keywords">isinstance</a>(t2)); //测试4:凡是和null相关的都是false Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println(Object.class.<a href="https://www.jb51.cc/tag/isinstance/" target="_blank" class="keywords">isinstance</a>(null)); Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println(D.class.<a href="https://www.jb51.cc/tag/isinstance/" target="_blank" class="keywords">isinstance</a>(null)); }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码