• 重写equals方法发现的一点问题


    这里假设有一个父类为Food,其子类为Apple,现在我们要在Apple中重写equals方法,但是测试的时候,我们会控制一些其他的因素来发现比较结果的不同。

    情况1:

    // 父类 Food
    1
    public class Food { 2 public void sayName(){ 3 System.out.println("我是父类food"); 4 } 5 }
     // 子类 Apple
    1
    public class Apple extends Food{ 2 @Override 3 public void sayName(){ 4 System.out.println("我是苹果"); 5 } 6 7 public void more(){ 8 System.out.println(" this is my own method"); 9 } 10 11 public String name ="红富士1号"; //我们直接在类中进行初始化赋值。 12 public int no=1; 13 14 @Override 15 public boolean equals(Object obj) { 16 if(obj == this){ 17 return true; 18 } 19 if(obj instanceof Apple ){ 20 Apple a1= (Apple)obj; 21 return this.name==a1.name && this.no==a1.no; 22 } 23 24 return false; 25 } 26 }
     // 测试类
    1
    public class test { 2 public static void main(String[] args) { 3 Apple a1= new Apple(); 4 5 Apple a2= new Apple(); 6 7 boolean result1 = a1.equals(a2); 8 System.out.println(result1); 9 } 10 }

    //输出结果是true,这看起来是意料之内的。

    情况2:

    Food 类不变
     // 改写 Apple 类
    1
    public class Apple extends food{ 2 @Override 3 public void sayName(){ 4 System.out.println("我是苹果"); 5 } 6 7 public void more(){ 8 System.out.println(" this is my own method"); 9 } 10 11 public String name ; // 我们改为在类中只声明,不初始化赋值。 12 public int no; 13 14 @Override 15 public boolean equals(Object obj) { 16 if(obj == this){ 17 return true; 18 } 19 if(obj instanceof Apple ){ 20 Apple a1= (Apple)obj; 21 return this.name==a1.name && this.no==a1.no; 22 } 23 24 return false; 25 } 26 }
     // 在测试类中新建了对象之后再给成员属性赋值
    1
    public class test { 2 public static void main(String[] args) { 3 Apple a1= new Apple(); 4 a1.name="红富士"; //在测试类中实例化了对象之后再赋值 5 a1.no=1; 6 7 Apple a2= new Apple(); 8 a2.name= "红富士"; 9 a2.no=1; 10 11 boolean result1 = a1.equals(a2); 12 System.out.println(result1); 13 } 14 }

    // 输出结果竟然是 false

    情况3:

    Food类和Apple类都不变
    // 我们在测试类中,先用父类声明来引用子类对象,然后在向下转型之后才给其成员属性赋值
    1
    public class test { 2 public static void main(String[] args) { 3 Apple a1= new Apple(); 4 a1.name="红富士"; 5 a1.no=1; 6 7 Food f1 = new Apple(); 8 Apple a2 = (Apple)f1; //向下转型后再赋值 9 a2.name= "红富士"; 10 a2.no=1; 11 12 boolean result1 = a1.equals(a2); 13 System.out.println(result1); 14 } 15 }

    // 最后输出结果竟然又成了 true!

    综上,这是为什么? 今天复习的时候无意中发现的这个问题,我一下子还没想明白。。。

  • 相关阅读:
    Codeforces Round #336 B
    Codeforces Round #336 A
    hiho一下157
    Codeforces Round #420 E
    Codeforces Round #420 C
    Codeforces Round #420 B
    Codeforces Round #420 A
    Codeforces Round #418 C
    Codeforces Round #418 B
    CodeForces 811D Vladik and Favorite Game bfs,模拟
  • 原文地址:https://www.cnblogs.com/tangshun100/p/13040784.html
Copyright © 2020-2023  润新知