|--需求说明
要求通过毛色,名字,品种来判定两条狗是不是同一条狗
|--实现方法
通过重写equals方法,对比毛色,名字,品种,这几个属性一致,则判定是同一条狗
|--代码内容
1 public class Dog { 2 private String name; 3 private String color; 4 private String breed; 5 6 public Dog() { 7 } 8 9 public Dog(String name, String color, String breed) { 10 this.name = name; 11 this.color = color; 12 this.breed = breed; 13 } 14 15 @Override 16 public boolean equals(Object obj) { 17 if (this == obj) { 18 return true; 19 } 20 if (!(obj instanceof Dog)) { 21 return false; 22 } 23 Dog dog = (Dog)obj; 24 if (this.name.equals(dog.name)&&this.breed.equals(dog.breed)&&this.color.equals(dog.color)){ 25 return true; 26 }else { 27 return false; 28 } 29 } 30 }Dog类
1 public class DogTest { 2 public static void main(String[] args) { 3 Dog dog1 = new Dog("小黄", "白色", "中华田园犬"); 4 Dog dog2 = new Dog("小黄", "白色", "中华田园犬"); 5 6 if (dog1.equals(dog2)) { 7 System.out.println("这两只狗是同一只狗"); 8 } else { 9 System.out.println("这两只狗不是同一只狗"); 10 } 11 } 12 }测试Dog类
|--运行效果
|--将重写equails的部分注销掉之后的运行结果
|--将Dog类重新增加注释发出来
1 public class Dog { 2 private String name; 3 private String color; 4 private String breed; 5 //无参构造方法 6 public Dog() { 7 } 8 //带参构造方法 9 public Dog(String name, String color, String breed) { 10 this.name = name; 11 this.color = color; 12 this.breed = breed; 13 } 14 //重写equails方法 15 @Override 16 public boolean equals(Object obj) { 17 //如果传入的对象和对象本身一致,则判定是同一只 18 if (this == obj) { 19 return true; 20 } 21 //如果对象不属于Dog类,则判定不是同一类 22 if (!(obj instanceof Dog)) { 23 return false; 24 } 25 //将传入类转化为Dog类 26 Dog dog = (Dog)obj; 27 //给出比对条件,比较name,breed,color三个属性,三个属性一致,则是同一条狗 28 if (this.name.equals(dog.name)&&this.breed.equals(dog.breed)&&this.color.equals(dog.color)){ 29 return true; 30 }else { 31 return false; 32 } 33 } 34 }