【发布时间】:2025-12-30 03:40:11
【问题描述】:
我正在尝试编写一个程序 (Driver),它将创建 Humans 及其 Pets 和特定类型,如下所示。
我遇到了多个错误:在 Driver 程序中,错误是当我尝试执行 Humans b = new Humans(); 时,我得到:
constructor Humans in class Humans cannot be applied to given types.
此外,如果我尝试写出Humans b = new Humans("Jane", Pet/Dog...),我不确定如何指定该人的宠物类型。
任何帮助和指导将不胜感激。
public class Humans {
String name;
Pets pet;
int popcount;
public Humans(String hname, Pets hpet) {
name = hname;
pet = hpet;
}
public int populationCount() {
return popcount;
}
public void makePetMakeNoise() {
int randnum = (int) (Math.random() * 10);
pet.makeNoise(randnum);
}
public void feedPet() {
pet.eat();
}
}
public class Pets {
String name;
String noise;
boolean canMakeNoise;
public Pets(String pname, String pnoise, boolean pcanmakenoise) {
name = pname;
noise = pnoise;
pcanmakenoise = canMakeNoise;
}
public void makeNoise(int number) {
if (canMakeNoise != false) {
for (int i = 0; i < number; i++) {
System.out.println(noise + name);
}
} else {
System.out.println(name + " *remains silent*");
}
}
public void eat() {
System.out.println(name + " is eating...");
}
class Dog extends Pets {
public Dog(String pname, String pnoise, boolean pcanmakenoise) {
super(pname, pnoise, pcanmakenoise);
}
public void eat() {
System.out.println(name + " is eating...");
}
}
class Cat extends Pets {
public Cat(String pname, String pnoise, boolean pcanmakenoise) {
super(pname, pnoise, pcanmakenoise);
}
public void eat() {
super.eat();
System.out.println("I'm still hungry, meow");
}
}
}
public class Driver {
public Driver() {
Humans b = new Humans();
b.name = "Jane";
Pets bb = new Pets(Cat);
b.pet = bb;
bb.canMakeNoise = true;
bb.name = "Bertha";
ArrayList<String> list = new ArrayList<String>();
list.add(b);
ListIterator<String> itr = list.listIterator();
while (itr.hasNext()) {
String str = itr.next();
str.makePetMakeNoise();
str.feedPet();
}
System.out.println(Humans.populationCount());
}
}
【问题讨论】:
-
您好,欢迎来到 Stack Overflow!请尽量只提供clear and minimal example;您的代码在这里太长了!
-
最好考虑一下每个类的对象代表什么。在您的情况下,
Humans的对象代表一个人类,因此最好将您的类命名为Human(不带 s)。Pets也是如此。只有当类的对象确实代表多个(例如人类列表)时,才使用复数是一个好主意。
标签: java oop object subclass superclass