创建一个用Java添加对象的方法

时间:2014-10-06 04:06:51

标签: java object arraylist

*编辑:我提出的问题是错误的,导致很多问题。 donatePet()应该只是将一个对象添加到列表中。所有必要的是拿一个对象并将它存储在一个arraylist中。

    Input :

    Cat, CatName5, 2, Brown, rawr, 2
    Cat, Kitty, 7, Yellow, a kitty cat, 6
    Dog, DogName3, 120, Grey, This is a dog, 3

前:

public static void donatePet(List<Pets> petList, Pets p) 
{

    petList.add(p);

}

donatePet()将出现在“测试”类中。 (将访问继承类的类。)

由回答者完成的转换已完成,因此您可以访问属于Pet类的方法。

1 个答案:

答案 0 :(得分:2)

致电createPetType()。在这种情况下,请存储每个lineArray的引用。

例如createPetType

//change method signature as per your requirement
private void createPetType(String[] lineArray) {
    //now, based on the assumption that lineArray[0] element will always have the type of Pet in it.
    if ("Dog".equalIgnoreCase(lineArray[0])) {
       //create Dog class instance
       //once you have the appropriate Pet instance
       //call donatePet method to donate
       //similarly for Cat and Other class
    }
}

现在,在donatePet()内 - 如果您想要对Pet类型执行特定操作,请使用instanceof

例如 -

donatePet(Pet p) {
    if (p instanceof Dog) {
       //if you are here, it means the Pet type passed to your method is of type 'Dog'
       //do whatever you want to do here
       //to cast Pet to Dog
       Dog g = (Dog) p;
       //call the methods relevant to 'g' type
       //add these instances to a list which will help you with listAvailablePets()
    }
}