object o = new Var(); 这样你就可以casting了:(Var)o.keyword 或者也可以这样 if(o instanceof Var){ (Var)o.keyword; }
可以分以下几个方面来讨论: 编译时出错 运行时出错 Run-Time Type Identification/Binding举一个例子来讨论:class Father{} class Son extends Fatrher{} class Another1{} class Another2{}public class Test{ public static void main(String[] args){ //无编译时错误,无运行时错误 Son s=new Son(); Father f=s; //无编译时错误,无运行时错误,因为是父类到子类,所以要显式casting Father f=new Son(); Son s=(Son)f;
//无编译时错误,有运行时错误:无法实时casting Father f=new Father(); Son s=(Son)f; //有编译时错误:incompatible types Father f=new Father(); Son s=f; //有编译时错误:incompatible types Another1 an1=new Another1(); Another2 an2=(Another2)an1; //有编译时错误:incompatible types Another1 an1=new Another1(); Another2 an2=an1; } }Object是所有类的父类,所以天生可当作上面例子中的Father
这样你就可以casting了:(Var)o.keyword
或者也可以这样
if(o instanceof Var){
(Var)o.keyword;
}
编译时出错
运行时出错
Run-Time Type Identification/Binding举一个例子来讨论:class Father{}
class Son extends Fatrher{}
class Another1{}
class Another2{}public class Test{
public static void main(String[] args){
//无编译时错误,无运行时错误
Son s=new Son();
Father f=s; //无编译时错误,无运行时错误,因为是父类到子类,所以要显式casting
Father f=new Son();
Son s=(Son)f;
//无编译时错误,有运行时错误:无法实时casting
Father f=new Father();
Son s=(Son)f; //有编译时错误:incompatible types
Father f=new Father();
Son s=f; //有编译时错误:incompatible types
Another1 an1=new Another1();
Another2 an2=(Another2)an1; //有编译时错误:incompatible types
Another1 an1=new Another1();
Another2 an2=an1;
}
}Object是所有类的父类,所以天生可当作上面例子中的Father