对象作为数组

时间:2010-03-21 17:06:03

标签: java arrays constructor

我需要创建类Dog和PurebredDog扩展Dog。问题是Dog可以同时是单个对象和对象数组(Dogs和PurebreedDogs:

 Dog pack[]={new Dog(76589,"As","black",18,
                    "Ann","Kowalsky"),
           new PurebreedDog(45321,"Labrador","Elf","black",25, 
                          "Angus","Mati","Barbara","Smith"),
           new Dog(102467,"Gamma","brown",89,
                    "Josh","Coke"),
            new PurebreedDog(9678,"York","Theta","brown",8,
                    "Emka","Figaro","Alice","Cat")};    

for(int i=0; i < pack.length; i++)
  System.out.println(pack[i]+"\n\n");

如何为Dog编写适当的构造函数? 你可以这样做:

public Dog(String name, etc){
}

但如何编写狗阵列的构造函数?

public Dog(Dog[]tab) ?

然后如何回忆它的元素? pack[]是2d数组吗?

4 个答案:

答案 0 :(得分:5)

为简化起见,Dog的实例确实应该引用一只狗。所以你的构造函数看起来应该类似(数据类型只是例子):

Dog(int ID, String color, String name, ...)

PurebreedDog将子类Dog并提供任何其他构造函数参数(和成员),例如breed等。

为了处理多只狗,我建议您将该类的实例存储在ListHashTable或其他类型的数据结构中,以便容纳多个元素。您使用的实际结构将取决于您的要求。

答案 1 :(得分:1)

在您的具体情况下,Dog代表一只狗,我同意贾斯汀的回答。

为了完整起见,我认为值得一提的是composite pattern

在某些情况下,对象的聚合可以与其各个部分的行为相同。传统示例是文件夹/文件层次结构。两者都响应相同的方法,例如sizedelete等。

如果您打算为家谱树建模,那么甚至可以使用Dog示例。狗是狗,但可以有 N 孩子。

答案 2 :(得分:1)

制作一只狗和许多狗的表现形式的方法是每个实体都是一个列表。单狗实体只是一个包含一只狗的列表;当然,多犬实体中不止有一只狗。但是你需要编码的只是(单个)Dog,然后,正如Justin和ewernli所说,使用Collection - 可能是Dog的ArrayList。

试图使未入伍的单身狗与狗列表“相同”只是疯了。

答案 3 :(得分:0)

好的,以下方式也是如此:

PurebreedDog类:

public class PurebreedDog extends Dog {

private String breed;
private String mother;
private String father;

public PurebreedDog(int id, String breed, String name, String color, int age,
        String owner_name, String owner_surname, String mother, String father){
    super(id, name, color, age, owner_name, owner_surname);
    this.breed = breed;
    this.mother = mother;
    this.father = father;
}

@Override
public String toString(){
    return super.toString()+"\n Pure breed dog \n"+"-------------------------------\n"+
            "BREED: "+this.breed+"\n"+"MOTHER: "+this.mother+"\n"+
            "FATHER: "+this.father+"\n-------------------------------";
}

}

狗班:

public class Dog {

private int id;
private String name;
private String owner_name;
private String owner_surname;
private String color;
private int age;
private Dog[]pack;

public Dog(int i, String n, String c, int w, String on, String os){
    id = i;
    name = n;
    color = c;
    age = w;
    owner_name = on;
    owner_surname = os;
}

public Dog(Dog[]p){

    Dog[]group = new Dog[p.length];
    for(int i=0; i < p.length; i++){
        group[i] = p[i];
    }

    this.pack = group;

}

@Override
public String toString(){

    return "-------------------------------\n"+
            "idr: "+this.id+"\n"+"OWNER: "+this.owner_name+
            this.owner_surname+"\n"+"NAME: "+this.name+"\n"+
            "color: "+this.color+"\n-------------------------------";
}