Topic: instanceof 关键词探幽 |
Print this page |
1.instanceof 关键词探幽 | Copy to clipboard |
Posted by: bujinwang Posted on: 2005-02-25 02:58 我们都知道instanceof测试一个实例是不是一个类的实例。那么如果你认为一个Dog 的dog instanceof Object 会返回假,那你就大错特错了。对于所有的父类(super) 类,instanceof 测试都会返回真。 我们来看这个例子:
结果是
所有测试都为真。 那么 如果我想知道一个实例是否是一个类,而不是父类(super classes)的实例怎么办呢:那就是用0o.getClass().equals(Dog.class)测试: 我们再看例子:
结果是:
有意思吧。(申请加分) |
2.Re:instanceof 关键词探幽 [Re: bujinwang] | Copy to clipboard |
Posted by: 孤独王子 Posted on: 2005-03-01 10:36 if(c2.getClass().equals(Base.class)){ System.out.println("c2: " + c2 + ", is of Ext1 class exactly"); } 这个应该是print if(c2.getClass().equals(Base.class)){ System.out.println("c2: " + c2 + ", is of Base class exactly"); } |
3.Re:instanceof 关键词探幽 [Re: bujinwang] | Copy to clipboard |
Posted by: aroundall Posted on: 2005-05-15 17:34 子类的对象是父类的对象! |
4.Re:instanceof 关键词探幽 [Re: bujinwang] | Copy to clipboard |
Posted by: truthawp Posted on: 2005-08-08 11:56 请大家帮忙看看这样一个问题: Teacher和Student都是类Person的子类 Person p;Teacher t;Student s; (p,t,s都是非空值) If (t instanceof Person){s=(Student)t;}这个语句导致的结果是: 答案上说是编译时错误,那是为什么呢? 那p,t,s是什么呢?从(t instanceof Person)这句看,t应该是对象;从(p,t,s都是非空值)和{s=(Student)t;}看,p,t,s象是变量;是不是编译错就是因为这个呢? 因为是程序片段,所以没法自己运行试了 |
5.Re:instanceof 关键词探幽 [Re: bujinwang] | Copy to clipboard |
Posted by: ranchgirl Posted on: 2005-08-08 13:21 You are not allowed to cast Teacher t to sibbling Student !!! If (t instanceof Person){s=(Student)t;} Teacher is a Person. Student is a Person. But Teacher is not a Student!!! Give you a working code, read, compile, run, play and change it, please! Pay attention to the comments inside
|
6.Re:instanceof 关键词探幽 [Re: bujinwang] | Copy to clipboard |
Posted by: truthawp Posted on: 2005-08-08 16:36 Teacher is a Person. Student is a Person. But Teacher is not a Student!!! 简单明了,谢谢版主. 给我这个程序很形象 这样理解起来就很容易了 |
7.Re:instanceof 关键词探幽 [Re: bujinwang] | Copy to clipboard |
Posted by: ranchgirl Posted on: 2005-08-08 23:38 Thanks! However, I have forgot to put off my disclaimer logo: Danger!!! Don't try this at work! P.S. The code is for teaching purpose only, not a good code example for real world. |
8.Re:instanceof 关键词探幽 [Re: bujinwang] | Copy to clipboard |
Posted by: awardwy Posted on: 2005-09-04 08:55 explain beautiful |
Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1 客服电话 18559299278 客服信箱 714923@qq.com 客服QQ 714923 |