![](/img/trans.png)
[英]How can I use 1 array with 2 different sizes using inheritance and constructors
[英]How to add 2 different animals into a text file using inheritance, if they have different constructors?
我正在嘗試使用繼承將2種不同的動物添加到文本文件中(貓和狗)。 問題是,它們具有不同的構造函數,我不確定如何將它們分別放入程序中到同一文本文件中,因為程序還使用用戶界面。
我不確定是否理解您的問題。
您有一個寫入狗和貓信息的文本文件。 您想將它們傳遞到您的程序中。 該文本文件由您控制嗎? 當您開始閱讀它時,您能理解它一開始是貓還是狗? 像animal type: cat
一樣animal type: cat
animal name: fluffy
...如果是這樣:
int numAnimals = infile.nextInt();
infile.nextLine();
kennel.setName(kennelName);
for (int i = 0; i < numAnimals; i++) {
if(infile.nextLine().equals("cat")) {
Cat cat = readCat(infile);
kennel.addAnimals(cat);
}
else if(infile.nextLine().equals("dog")){
Dog dog = readDog(infile);
kennel.addAnimals(dog);
}
}
public Dog readDog(Scanner infile) {
//same as your dog reading part except the last part
return new Dog(animalName, owners, likesBones, favFood,
feedsPerDay);
}
為貓寫同樣的方法,然后就可以了。 由於Dog類是從動物類繼承的,因此dog也是動物。 因此,您可以將它作為動物添加到您的動物列表中。 希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.