gpt4 book ai didi

java - 属于父类(super class)的不同类的对象的ArrayList?

转载 作者:行者123 更新时间:2023-12-01 08:15:08 25 4
gpt4 key购买 nike

在下面的代码中,“<”和“>”之间应该放置什么,以便我能够添加 Animal 父类(super class)的每个子类的新对象?

package animal;

import javax.swing.JOptionPane;
import java.util.ArrayList;

public class Animal {

public static void main(String[] args) {
Animal createAnimals = new Animal();
createAnimals.userInputHandle();

ArrayList <> animalList = new ArrayList<>();
animalList.add(new Dog);

}

private String userInputHandle(){

String userInput;
userInput = JOptionPane.showInputDialog("Select animal from the "
+ "following list"
+ "\n1.Dog\n2.Cat\n3.Snake\n4.Frog"
+ "\n5.Human\n6.Shark\n7.Sea Gulls");
userInput = userInput.toLowerCase();

return userInput;}
}

class Fish extends Animal{




}
class Amphibians extends Animal{

}
class Reptiles extends Animal{}
class Birds extends Animal{}

这样我将在 Animal 类中创建一个方法并为每个子类重写它。例如对于两栖类--> Frog 属于两栖类等等。

最佳答案

// this will work fine as 'Animal' will be base class for other class
ArrayList <Animal> animalList = new ArrayList<Animal>();
//
animalList.add(new Reptiles());
animalList.add(new Birds());
animalList.add(new Amphibians());

关于java - 属于父类(super class)的不同类的对象的ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14072628/

25 4 0