gpt4 book ai didi

Java初始化一个子类

转载 作者:行者123 更新时间:2023-12-04 00:32:54 25 4
gpt4 key购买 nike

初始化接口(interface)的实现类的合适方法是什么(由某些逻辑确定)

例子

IAnaimal is an interface
Cat -> IAnimal
Dog -> IAnimal
Cow -> IAnimal


int x = in.nextInt();
IAnimal animal = null;

if(x==1)
animal = new Dog();
else if(x==2)
animal = new Cat();
else
animal = new Cow();

animal.destroyManKind();

这是正确的做法吗?有没有“更”专业的方法来做到这一点?

最佳答案

我会有一种更简洁的方式来读取名称而不是 1、2 和 3,但在这种情况下您可以使用开关。

int choice = in.nextInt();

switch(choice) {
case 1: animal = new Dog(); break;
case 2: animal = new Cat(); break;
default: animal = new Cow(); break;
}

或者使用字符串开关

String choice = in.next();

switch(choice.toLowerCase()) {
case "dog": animal = new Dog(); break;
case "cat": animal = new Cat(); break;
case "cow": animal = new Cow(); break;
default: // error
}

关于Java初始化一个子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14126263/

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