【问题标题】:ArrayList of Objects of different classes that belong to a superclass?属于超类的不同类的对象的ArrayList?
【发布时间】:2012-12-13 21:40:11
【问题描述】:

在下面的代码中,应该在“”之间放置什么,以便我能够添加动物超类的每个子类的新对象?

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 类中创建一个方法并为每个子类覆盖它。例如对于两栖类--> 青蛙属于两栖类等等。

【问题讨论】:

  • 它只会是“Animal”,因为您将从“Animal”类派生该类的其余部分

标签: java arraylist


【解决方案1】:

像这样在 ArrayList 上声明。

ArrayList <Animal> animalList = new ArrayList<Animal>();

添加 Animal 的子类。

animalList.add(new Monkey());
animalList.add(new Donkey());

等等。

如果您使用 Java SE7 实例化 Generic(在您的情况下为 ArrayList)的另一种方法是使用像这样的有限类型推断。

ArrayList <Animal> animalList = new ArrayList<>();

【讨论】:

    【解决方案2】:
    // 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());
    

    【讨论】:

    • 这解决了它。感觉很愚蠢,也无法弄清楚这一点。谢谢。
    • 欢迎您,随时将问题标记为已解决,因为这也将帮助其他学习者!
    • 在编程的世界里没有什么像愚蠢一样的东西,一切都是一种体验,而我在人生的某个时刻也走上了同样的道路:P!
    【解决方案3】:

    如果你做出声明

    ArrayList <Animal> animalList = new ArrayList<Animal>(); 
    

    然后您就可以向其中添加 Animal 的任何子类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-17
      • 2015-06-22
      • 1970-01-01
      • 2013-04-06
      • 1970-01-01
      • 2014-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多