Java - equals method in base class and in subclasses

前端 未结 8 986
自闭症患者
自闭症患者 2020-11-30 06:45

I have a simple base class, which is later extended by many separate classes, which potentially introduce new fields, but not necessarily. I defined an equals method in the

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 07:12

    If you do not write you code correctly it will creates a serious problem, called asymmetry (violates contract for equality) so lets see our options.

    Best Practice – Same Classes Strategy. If B is a subclass of A and each class has its own equals method, implemented using the same classes strategy, then the class B should be declared final to prevent the introduction of an asymmetric definition of equals in any future subclass of B.

    Question. What if we don’t wish to make B final?

    Use Composition instead of Inheritance. Whenever classes B and A, where B is a subclass of A, require different equals methods, using composition instead of inheritance is a good strategy, and if making the class B final is not an option, it is the only safe way to handle equals.

    How?

     public class A{
    public boolean equals(Object ob){
    //write your code here
    }
    }
    
    class B{
    A a= new A();
    public B(A a){
    this.a= a;
    }
    public boolean equals(Object ob){
    //...write your code here
    if(!((B)ob).a).equals(a)) return false;
    //...write your code here
    
    }
    }
    

提交回复
热议问题