gpt4 book ai didi

java - 缩小实现中的论点

转载 作者:行者123 更新时间:2023-11-29 04:49:37 24 4
gpt4 key购买 nike

出于培训目的,我正在创建 Java 项目来保存有关动物的信息。有一个其他将扩展的抽象类 Animals。

我想创建食肉界面,通常会将任何动物作为参数:

    public interface Carnivorous {

public void eatAnimal(Animal animal);
//alternative way I have tried
public <T extends Animal> void eatAnimal2( T animal);
}

问题是在具体实现中我想将其缩小到扩展 Animal 的特定类:

public class Cat extends Animal implements Carnivorous {


public Cat(String name, int expierence, String meow) {
super(name, expierence);
this.meow = meow;
}

public String getMeow() {
return meow;
}

public void setMeow(String meow) {
this.meow = meow;
}

@Override
public String toString() {
return "Cat [meow=" + meow + ", name=" + name + ", expierence=" + expierence + "]";
}

@Override
public void eatAnimal(Animal animal) {
// TODO Auto-generated method stub

}

@Override
public <T extends Animal> void eatAnimal2(T animal) {
// TODO Auto-generated method stub

}

在这种情况下,我希望猫只吃老鼠。我不喜欢吃斑马。

最佳答案

您可以在接口(interface)中使用泛型来帮助进行类型检查。

public static class Animal {

public Animal() {
}
}

public static class Rodent extends Animal {

public Rodent() {
}
}

public interface Carnivorous<A extends Animal> {

public void eatAnimal(A animal);
}

public class Cat extends Animal implements Carnivorous<Rodent> {

@Override
public void eatAnimal(Rodent r) {
}

}

这里我有一只食肉动物,它只吃啮齿动物

关于java - 缩小实现中的论点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35895166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com