在java中强制类型转换分为基本数据类型和引用数据类型两种,这里讨论引用数据类型。
在Java中由于继承和向上转型,子类可以非常自然地转换成父类,但是父类转换成子类则需要强制转换。因为子类拥有比父类更多的属性、更强的功能,所以父类转换为子类需要强制。
构建 Son 和 Father 两个类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Father{ public void eat(){ System.out.println( "father is eating!" ); } public void sleep(){ System.out.println( "father is sleeping!" ); } } class Son extends Father{ public void sleep(){ System.out.println( "son is sleeping!" ); } public void play(){ System.out.println( "son is playing!" ); } } |
首先构造一个Son对象,然后用一个Father类型变量引用它:
1 | Father father = new Son(); |
在这里Son 对象实例被向上转型为father了,但是请注意这个Son对象实例在内存中的本质还是Son类型的,只不过它的能力临时被消弱了而已,现在我们将其对象类型还原!
1 | Son son = (Son) father; |
其实father引用仍然是Father类型的,只不过是将它的能力加强了,将其加强后转交给son引用了,Son对象实例在son的变量的引用下,恢复真身,可以使用全部功能了。
看一下整体效果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Father father = new Son(); father.sleep(); father.eat(); System.out.println( " " ); Father f = new Son(); Son son = (Son) f; son.eat(); son.sleep(); son.play(); } } |
程序输出:
1 2 3 4 5 6 | son is sleeping! father is eating! father is eating! son is sleeping! son is playing! |