java中instanceof是怎么用的
instanceof关键字
instanceof是java中固有的关键字, 就像main, public一样,用法:aa instanceof AA 就是问aa是不是AA的一个实例, 是的话,就返回真。马 克 - t o - w i n:当用instance of测试时,马克-to-win:子类的指针是一个instance of父类, 返回值为真,见以下的例子。
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
例1.9.2
class AMark_to_win {
}
class B {
}
class AA extends AMark_to_win {
}
public class Test {
public static void main(String[] args) {
AMark_to_win a = new AMark_to_win();
AMark_to_win aa = new AA();
B b = new B();
AA aaa = (AA) aa;
AA aaaa = new AA();
System.out.println(a instanceof AA);// false
System.out.println(aa instanceof AA);// true
System.out.println(a instanceof AMark_to_win);// true
System.out.println(b instanceof B);// true
System.out.println(aa instanceof AMark_to_win);// true//think of AMark_to_win aa=nul;马克-to-win:
System.out.println(aaa instanceof AA);// true
/* true aaa is an instance of AA,AA is a A, (is relationship. ) */
System.out.println(aaa instanceof AMark_to_win);
System.out.println(aaaa instanceof AMark_to_win);// true,AA is a AMark_to_win, (is relationship. )
// System.out.println(a instanceof B);//compile error: inconvertible type
}
}
result is:
false
true
true
true
true
true
true
true