标签:blog 使用 ar java div c log r new
instanceof是java的一个关键字,用于判断运行的一个对象是否是一个特定类的实例,instanceof返回一个boolean,如果该对象是特定类的一个实例,返回true,反之为false.
class instanceofDemo
{
public static void main(String[] args)
{
CFather c1 = new CChild1();//父类对象引用指向子类对象
test(c1);
CFather c2 = new CChild2();
test(c2);
}
public static void test(CFather c){
c.print();
//使用instanceof判断c是否是CChild2的一个实例
if (c instanceof CChild2){
CChild2 c2 = (CChild2)c;
c2.print1();
}
}
}
abstract class CFather{
abstract public void print();//抽象方法
}
class CChild1 extends CFather{
//
public void print(){
System.out.println("this is Child1");
}
}
class CChild2 extends CFather{
public void print(){
System.out.println("this is Child2");
}
//本类的其他方法
public void print1(){
System.out.println("hello java");
}
}
标签:blog 使用 ar java div c log r new
原文地址:http://www.cnblogs.com/qthomas/p/4006450.html