代码解释多态 转型问题:
public class Polymorphic {
public static void main(String [] args){
//多态-----动态绑定(后期绑定)
//程序运行时根据具体参数地址找到内存对象 从而能够正确执行对应的方法。
ShapeController objShapeController = new ShapeController();
Shape objShape = new Circle();
objShapeController.doActive(objShape); // 结果:Circle.draw Circle.move
objShape = new Square();
objShapeController.doActive(objShape); // 结果:Square.draw Square.move
//向上转型:安全的 但可能会丢失子类数据
Shape objShape11 = new Circle();//向上转型
objShape11.draw();//结果:Circle.draw . objShape11引用指向 new Circle()的地址。
//objShape11.ping(); //此方法掉不通。----方法丢失
//向下转型:不安全 必须知道确切的类型 并且执行过程中是程序效率降低(执行类型检查)
Shape objShape22 = new Circle();//向上转型
((Circle)objShape22).ping();//向下转型。 必须知道具体的子类类型 执行强制转换
objShape22 = new Square();
//((Circle)objShape22).ping();//结果:ClassCastException
//((Circle)objShape22).draw();//结果:ClassCastException
}
}
class ShapeController{
void doActive(Shape objShape){
objShape.draw();
objShape.move();
}
}
class Shape{
void draw (){};
void move (){};
}
class Circle extends Shape{
@Override
void draw() {
System.out.println("Circle.draw");
}
@Override
void move() {
System.out.println("Circle.move");
}
void ping(){
System.out.println("Circle.ping");
}
}
class Square extends Shape{
@Override
void draw() {
System.out.println("Square.draw");
}
@Override
void move() {
System.out.println("Square.move");
}
void tt(){
System.out.println("Square.tt");
}
}