我有一个动物园程序,在动物园里有爬行动物的分支动物群。当我执行 equals 方法时,主程序会编译并运行。我很困惑,如果我比较的是对象而不是特定的 int 或 String,java 怎么知道使用 equals 方法?
public class Zoo {
public static void main(String[]args) {
Animal a=new Animal("Bob");
Reptile komodo= new Reptile("Snakey");
komodo.bask();
a.size=3;
komodo.size=5;
System.out.println(a);
System.out.println(komodo);
Turtle t= new Turtle("Slowy");
t.hide();
t.size=6;
t.numlegs=4;
System.out.println(t);
System.out.println(t.equals(komodo));
}
}
public class Animal {
public String name;
public boolean equals(Animal other) {
return other.size==this.size;
}
public Animal(String s) {
name=s;
}
public void setName(String n) {
this.name=n;
}
public void eat(String meal) {
System.out.println("chump chump yummy "+meal);
}
public int size;
public String toString() {
return "I am "+name+" and I'm "+size+" cm long";
}
}
public class Reptile extends Animal {
public Reptile(String n) {
super(n);
numlegs=0;
}
public Reptile(String n, int l) {
super(n);
numlegs=l;
}
public void bask() {
System.out.println("basking...");
}
public String toString() {
return super.toString()+numlegs+" legs";
}
public int numlegs;
}
public class Turtle extends Reptile {
public Turtle(String n) {
super (n,4);
shellColor="Brown";
}
public void hide() {
System.out.println("you cant see me");
}
public String toString() {
return super.toString()+" and my shell is"+ shellColor;
}
public String shellColor;
public void bask() {
super.bask();
System.out.println("turtle is basking...");
}
}
最佳答案
您不是在覆盖 Object#equals
方法,而是在重载它。在您的方法声明中,您使用 Animal
类型而不是 Object
:
public boolean equals(Animal other)
该方法的一个很好的覆盖是使用 instanceof
运算符。显示示例:
@Override
public boolean equals(Object other) {
if(other instanceof Animal) {
Animal otherAnimal = (Animal)other;
//comparison logic...
}
return false;
}
有关该主题的更多信息:
关于java - equals 方法是否适用于对象?如果是这样,如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17551280/