java return

来源:百度知道 编辑:UC知道 时间:2024/06/17 22:33:12
class Dog {
int color,weight,height;
public Dog(int color,int weight,int height) {
this.color=color;
this.weight=weight;
this.height=height;
}

public boolean equals(Object obj) {
if(obj==null) return false;
else {
if(obj instanceof Cat)
{
Dog d=(Dog) obj;
if(d.color == this.color && d.weight == this.weight && d.height == this.height) {
return true;
}
}

}
//return false;
}
}

public class TestEquals {
public static void main(String []args) {
Dog d1=new Dog(1,2,3);
Dog d2=new Dog(1,2,3);
System.out.println(d1==d2);
System.out.println(d1.equals(d2));
}
}
为什么我把以上代码中的最后一个return语句注释掉就会出错?请回答详细点 谢谢

因为你这个equals 方法是要求返回一个Boolean型的变量。虽然你if里有,但是如果条件都不满足2个if呢,那是不是没返回值了,但是方法要求返回啊。所以得加上。这都没搞清楚?基础不扎实哦。。。

那是的
如果你的IF条件不满足条件的话
你的equals方法将没return值
所以在程序编译的时候将不给通过

if(d.color == this.color && d.weight == this.weight && d.height == this.height) {
return true;
}
看这句话,如果这个if的条件为假不执行的话,这个方法就没有返回值了。所以系统默认必须有个返回值。明白了么?