欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

多态/区分对象类型转换(向上转型vs向下转型)

时间:2023-07-03
区分

向上转换:子类到父类转换;失去子类特有的方法,向上变成父类向下转换:父类到子类转换;拥有子类特有的方法,向下变成子类 举例多好用:向上转型-多态

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 mlist = new ArrayList(); public void add(Electronics electronics){ mlist.add(electronics); } public int getSize(){ return mlist.size(); } public Electronics getListItem(int position){ return mlist.get(position); }}public class Demo0209 { public static void main(String[] args) { final int THINKPAD =0; final int MOUSE =1; final int KEYBOARD =2; ShopCart car = new ShopCart(); car.add(new Thinkpad()); car.add(new Mouse()); car.add(new Keyboard()); System.out.println("购物车里电子产品数:"+car.getSize()); //取出来电脑,测试 //向下转型,让类实例重新获得了丢失的方法 Thinkpad thinkpad = (Thinkpad) car.getListItem(THINKPAD); thinkpad.boot(); System.out.println("------------"); //取出来鼠标,测试,略 //取出来键盘,测试,略 }}

以上例子来自Java向下转型的意义
注意:“需要把多种类型的实例对象,全都扔到一个集合”

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。