来源:http://blog.youkuaiyun.com/qq_20289209/article/details/52796655
http://blog.youkuaiyun.com/chenssy/article/details/14111307
大神的详解:点击打开链接
简单总结:
1.向上造型:即父类引用指向子类对象,可以自动转换。如:
Father father = new Son();
这里的引用father指向内存中对象实质还是Son类型,不过对象的功能被临时削弱为father。
2.向下转型:即强制类型转换。
被向上造型的对象进行强制类型转换是没有问题的:
Son son =(Son)father;
但是强转没有向上造型的对象会出现错误的:
Father father = new Father();
Son son = (Son)father;
- public class Father {
- public void test(){
- System.out.println("Father的test方法。。。。");
- }
-
- public void test1(){
- System.out.println("Father的test1方法。。。。");
- }
-
- public static void main(String[] args) {
-
- Father father = new Son();
- father.test();
- father.test1();
-
-
-
- Son son = (Son)father;
- son.test();
- son.test2();
-
-
- Father father2 = new Father();
- son = (Son)father2;
-
-
-
-
-
- }
- }
-
- class Son extends Father{
- public Son(){
- }
-
- public void test1(){
- System.out.println("Son的test1方法。。。。");
- }
-
- public void test2(){
- System.out.println("Son的test2方法。。。。");
- }
- }