所以我有这个动物园程序,我想要一个动物园中的房间列表,以及每个房间中的猫列表。
我有3个类:Felid
,Housecat
和Wildcat
-Housecat
和Wildcat
扩展Felid
。根据动物的字面类别(现在我有老虎,波斯,暹罗和猎豹-老虎和猎豹扩展了野猫,波斯和暹罗扩展了家猫),某些属性将自动分配。
类图-http://i.imgur.com/VTSNRVA.jpg
例如,这些是felid的字段:
String speciesName;
String furColour;
String gender;
int weightPounds;
boolean packAnimal;
String habitat;
int age;
这些是家猫的字段:
String ownerName;
String catName;
boolean feral;
这些是野猫的字段:
boolean manEater;
在我的家猫构造函数中,我有
if(catName == null || catName.equals("")){
feral = true;
}
如果是猫的野性,则当用户使用猫的名称创建HouseCat并使用“ printCatInfo()”时:
@Override
public void printCatInfo(){
if(feral){
System.out.println("feral" + "\n" + speciesName + "\n" + furColour + "\n" + gender +
"\n" + weightPounds + "lbs\n" + "is not a pack animal" + "\n" + habitat + "\n" + age + " years old (human)");
}
else{
System.out.println("owner name is: " + ownerName + "\n" + "cat name is: " + catName + "\n" + speciesName + "\n" + furColour + "\n" + gender +
"\n" + weightPounds + "lbs\n" + "is not a pack animal" + "\n" + habitat + "\n" + age + " years old (human)" + "\n");
}
}
它不会打印其名称。
feral
siamese
White or grey abdomen with black legs, face and tail
male
8lbs
is not a pack animal
urban
7 years old (human)
麻烦的是,我认为所有猫都属于野猫,因为我用于猫列表的列表是:
ArrayList<Felid> catList = new ArrayList<Felid>();
因此,我猜catName始终为null,因为添加到列表中的家猫只会算作“猫科动物”类型。
如何创建一个列表,我可以将所有的猫都扔进去,但仍然将它们视为各自的类?
编辑:感谢指出赋值运算符错误,虽然它仍然只打印野性
最终编辑:非常感谢'DoubleDouble'向我指出如何使用'Super()'-这不是我期望的问题。这是问题所在:
public class Siamese extends HouseCat{
public Siamese(int weightPounds, int age, String ownerName, String catName, String gender){
this.speciesName = "siamese";
this.furColour = "White or grey abdomen with black legs, face and tail";
this.ownerName = ownerName;
this.catName = catName;
this.weightPounds = weightPounds;
this.age = age;
this.gender = gender;
}
}
新代码:
public class Siamese extends HouseCat{
public Siamese(int weightPounds, int age, String ownerName, String catName, String gender){
super(catName);
this.speciesName = "siamese";
this.furColour = "White or grey abdomen with black legs, face and tail";
this.ownerName = ownerName;
this.catName = catName;
this.weightPounds = weightPounds;
this.age = age;
this.gender = gender;
}
}
最佳答案
您的构造函数似乎如下(如果我做错了,请纠正我):
public Siamese(int weightPounds, int age, String ownerName, String catName, String gender)
{
this.weightPounds = weightPounds;
this.age = age;
this.ownerName = ownerName;
this.catName = catName;
this.gender = gender;
}
public HouseCat()
{
if(catName == null || catName.equals(""))
{
feral = true;
}
}
由于
ownerName
,catName
和feral
都是HouseCat
类的一部分,因此最好让HouseCat
构造函数处理这些字段。public HouseCat(String ownerName, String catName)
{
this.ownerName = ownerName;
this.catName = catName;
if(catName == null || catName.equals(""))
{
feral = true;
}
}
连体语言如下:
public Siamese(int weightPounds, int age, String ownerName, String catName, String gender)
{
super(ownerName, catName);
this.weightPounds = weightPounds;
this.age = age;
this.gender = gender;
}