Java 不兼容类型、面向对象编程、人类和宠物可以是2种类型
我正在写一些课程:人类、宠物、狗和猫,这些课程扩展了宠物。当我在人类中调用makePetMakeNoise()方法时,它应该转到Pets中的makeNoise()方法并返回该方法。对于feedPet(),它应该做同样的事情,但eat()的猫狗方法将不同。现在,我得到了一个错误:不兼容的类型:void不能转换为int。。。当我试图从Pets类调用makeNoise()时。请帮我理解出了什么问题Java 不兼容类型、面向对象编程、人类和宠物可以是2种类型,java,oop,types,extends,bluej,Java,Oop,Types,Extends,Bluej,我正在写一些课程:人类、宠物、狗和猫,这些课程扩展了宠物。当我在人类中调用makePetMakeNoise()方法时,它应该转到Pets中的makeNoise()方法并返回该方法。对于feedPet(),它应该做同样的事情,但eat()的猫狗方法将不同。现在,我得到了一个错误:不兼容的类型:void不能转换为int。。。当我试图从Pets类调用makeNoise()时。请帮我理解出了什么问题 public class Humans { String name; Pets pet
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 int makePetMakeNoise() {
int randnum = (int) (Math.random() * 10);
return pet.makeNoise(randnum);
}
public void feedPet() {
pet.eat();
}
}
公共类宠物{
字符串名;
弦噪声;
布尔噪声;
公共宠物(字符串pname、字符串pnoise、布尔pcanmakenoise){
name=pname;
噪音=噪音;
pcanmakenoise=canMakeNoise;
}
公共void makeNoise(整数){
if(canMakeNoise!=false){
for(int i=0;i
你的makeNoise
方法在类Pets
中返回void
,但是当你在类Humans
中调用它时,你想返回你从中得到的值。由于makeNoise
不返回任何内容,语句int classHumans
将返回void
,但该方法定义为返回int
public int makePetMakeNoise(){}
将
int
更改为void
,并以相同的方法删除return
:makePetMakeNoise()
将人类类的定义更改为以下内容
import java.util.*;
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();
}
}
因为Pets类的makeNoise(int number)
方法是void
类型。更改makePetMakeNoise方法是人类类,如下所示:
public void makePetMakeNoise() {
int randnum = (int) (Math.random() * 10);
pet.makeNoise(randnum);
}
hpet.makeNoise返回void,但在Humans中返回intreturn hpet.makeNoise(randnum)
和public void makeNoise(int number)
我没有将public int makePetMakeNoise()更改为public void makepetnoise();或返回hpet.makeNoise(randnum);宠物。制造噪音(randnum);当我编辑这个问题时
public void makePetMakeNoise() {
int randnum = (int) (Math.random() * 10);
pet.makeNoise(randnum);
}