免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 810 | 回复: 0
打印 上一主题 下一主题

用instanceof检测对象的类型 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-09-28 15:23 |只看该作者 |倒序浏览

/**
* instanceof 用于检测对象的类型。
* (1)类的对象与类作instance of操作,结果为true
* (2)子类对象与父类作instance of操作,结果为true。
*  因此,所有对象与Object作instance of操作,结果都为true。
* (3)其他情况下,结果都为false。
*/
public class InstanceOf {
        
        // 父类
        static class ClassA {
        }
        // 子类
        static class ClassB extends ClassA{
        }
        public static void main(String[] args) {
                ClassA a = new ClassA();
                ClassB b = new ClassB();
                // 检测对象a,b是否为ClassA类型
                if (a instanceof ClassA){
                        System.out.println("Object a is a ClassA Object!");
                } else {
                        System.out.println("Object a is not a ClassA Object!");
                }
                if (b instanceof ClassA){
                        System.out.println("Object b is a ClassA Object!");
                } else {
                        System.out.println("Object b is not a ClassA Object!");
                }
               
                // 检测对象a,b是否为ClassB类型
                if (a instanceof ClassB){
                        System.out.println("Object a is a ClassB Object!");
                } else {
                        System.out.println("Object a is not a ClassB Object!");
                }
                if (b instanceof ClassB){
                        System.out.println("Object b is a ClassB Object!");
                } else {
                        System.out.println("Object b is not a ClassB Object!");
                }
        }
}
运行结果:
C:\java>java    InstanceOf
Object a is a ClassA Object!
Object b is a ClassA Object!
Object a is not a ClassB Object!
Object b is a ClassB Object!
文章引用自:

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/44063/showart_391852.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP