向上转型和向下转型代码如下(示例):
class Person1{ //人public void eat(Apple a){ //这里写 Apple就被固定了,这个方法只能放Apple类
}
public void eat(Fruit f){ //放入父类Fruit 又可以接收苹果 又可以接收香蕉 节约代码
}
}
class Fruit //水果 父类 { public void eat(){} } class Apple extends Fruit{ //苹果 继承父类 public void eat(){ System.out.println("苹果"); } public void play(){ System.out.println("吃"); } }class Banana extends Fruit //香蕉 继承父类 { }
向上转型: Fruit f = new Apple(); //把子类赋值给父类 f.eat(); //苹果 父类有eat方法通过 然后执行子类eat方法 向下转型: Apple a = (Apple)f; //把父类强行转换成子类 a.eat(); //父类子类都有的方法 a.play(); //苹果 父类调用了子类特有方法 通过向下转型就可以使用子类特有方法
总结
多态:1.节省代码,形参接收子类,改成形参接收父类,可以接收多种子类
2.转型:通过转型父类可以调用子类特有方法



