向上转换:子类到父类转换;失去子类特有的方法,向上变成父类向下转换:父类到子类转换;拥有子类特有的方法,向下变成子类 举例多好用:向上转型-多态
class Pet{ public void eat(){}}class Dog extends Pet{ @Override public void eat() { System.out.println("狗狗吃骨头"); }}class Cat extends Pet{ @Override public void eat() { System.out.println("喵喵吃鱼干"); }}class Master{ public void feed(Pet p){ p.eat(); }}public class Demo0609 { public static void main(String[] args) { Pet d = new Dog(); Pet c = new Cat(); Master m = new Master(); m.feed(d); m.feed(c); }}
举例多好用:向下转型-强制类型转换package www.csdn.p0209;import org.w3c.dom.Element;import java.util.ArrayList;import java.util.List;interface Electronics{}class Thinkpad implements Electronics{ public void boot(){ System.out.println("using Thinkpad"); }}class Mouse implements Electronics{ public void move(){ System.out.println("move the mouse"); }}class Keyboard implements Electronics { public void input(){ System.out.println("using Keyboard input"); }}class ShopCart{ private List
以上例子来自Java向下转型的意义
注意:“需要把多种类型的实例对象,全都扔到一个集合”