【JavaSE】 向上转型与向下转型问题

结论写在前面:向上转型不会出错,但是使用有限制,只能调用父类拥有的方法。

        向下转型可能会出错。

Animal() 和 Dog()类各自只写了两个方法,就不贴代码了,

测试代码如下:package java_test.java.cast;

import org.junit.Test;
/**
 * 定义:    Animal:            eat();sleep();
 *         Dog继承Animal:     eat()(重写父类方法); play()(子类独有方法);
 * @author sky
 *
 */
public class UpAndDown {

@Test
public void up(){ Animal a= new Dog();//向上转型 a.eat();//调用的是子类重写的父类的方法,dog eat fruit a.sleep();//调用的是父类的方法,因为子类没有重写这个方法,自然是调用父类的方法:Animal need sleep... // a.play();//不可以调用子类独有的方法。因为此时a是作为一个Animal,不是所有的Animal都可以play System.out.println("----------------"); Dog d=(Dog)a;//向上转型后再向下转型,再把a看做是dog,此时,向下转型是可以的 d.eat();//可以调用子类重写的父类的方法,dog eat fruit d.play();//可以调用子类独有的方法!!!,dog can play... d.sleep();//可以调用父类的方法,Animal need sleep... System.out.println("--------"); }

//  向下转型失败的例子 @Test
public void down(){ Animal a =new Animal(); a.eat();//当然可以正常调用 Dog d=(Dog)a;//类型转换出错:ClassCastException,因为不能把所有的动物都看成是dog // d.eat();//类型转换都出错了,就不必谈方法调用了,也是不可以的 // d.play(); // d.sleep(); } }

 

补充一个向上转型应用的小例子,参考资料:《Thinking in Java》(第四版)

Circle(),Triangle()和 Line()都继承了Shape()。

 

void doSomething(Shape shape) {

  shape.erase();

  // ...

  shape.draw();

}

This method speaks to any Shape, so it is independent of the specific type of object that it’s drawing and erasing. If some other part of the program uses the doSomething( ) method:

//这个方法的形参要求输入任意一个Shape类型的参数,它不需要传入具体的子类类型(不需要传入具体的子类对象),如果程序中的其它部分要调用doSomething( )这个方法:

Circle circle = new Circle();

Triangle triangle = new Triangle();

Line line= new Line();

doSomething(circle);

doSomething(triangle);

doSomething(line);

The calls to doSomething( ) automatically work correctly, regardless of the exact type of the object.

//doSomething( ) 这个方法会自动的正确运行,而不用管传入的对象的类型。

 

以上就是一个使用向上转型的例子。

posted @ 2017-10-10 15:38  张小全  阅读(316)  评论(0)    收藏  举报