在java里面强制类型转换是有条件的,一般只能将父类强制转换为子类,子类到父类是不需要强制转换的,而不同类型间是不能转换的。但是有一种情况例外,那就是一个Object对象,它可能是任何一种东西的实例,可以将之强制转换为其实际的类型,例如:
String a="dfd";
Object o=a;
String c=(String)o;
String a="dfd";
Object o=a;
String c=(String)o;
这样你就可以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