栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

包含相同超类的不同对象的ArrayList-如何访问子类的方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

包含相同超类的不同对象的ArrayList-如何访问子类的方法

实际上,从超类执行此操作不是一个好方法,因为每个子类的行为都不同。

为了确保您实际上在调用适当的

move
方法,请
Animal
从超类更改为接口。然后,当您调用该
move
方法时,您将能够确保为所需的对象调用适当的move方法。

如果要保留公共字段,则可以定义一个抽象类

Animalbase
,并要求所有动物都以此为基础,但是每个实现都需要实现该
Animal
接口。

例:

public abstract class Animalbase {    private String name;    private int age;    private boolean gender;    // getters and setters for the above are good to have here}public interface Animal {    public void move();    public void eat();    public void sleep();}// The below won't compile because the contract for the interface changed.// You'll have to implement eat and sleep for each object.public class Reptiles extends Animalbase implements Animal {    public void move() {        System.out.println("Slither!");    }}public class Birds extends Animalbase implements Animal {    public void move() {        System.out.println("Flap flap!");    }}public class Amphibians extends Animalbase implements Animal {    public void move() {        System.out.println("Some sort of moving sound...");    }}// in some method, you'll be calling the belowList<Animal> animalList = new ArrayList<>();animalList.add(new Reptiles());animalList.add(new Amphibians());animalList.add(new Birds());// call your method without fear of it being genericfor(Animal a : animalList) {    a.move();}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/419498.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号