java超类代表的对象比子类多_java – 包含同一超类的不同对象的ArrayList – 如何访问子类的方法...

从超类中确实没有很好的方法可以做到这一点,因为每个子类的行为都会有所不同.

要确保您实际调用适当的移动方法,请将Animal从超类更改为接口.然后,当您调用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 below

List animalList = new ArrayList<>();

animalList.add(new Reptiles());

animalList.add(new Amphibians());

animalList.add(new Birds());

// call your method without fear of it being generic

for(Animal a : animalList) {

a.move();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值