Super equals

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • odwrotnie
    New Member
    • Sep 2008
    • 9

    Super equals

    Hi,

    I have a class Range with 2 fields (starts and ends), it overrides equals() method:
    Code:
    public boolean equals(Object o) {
    		if(this == o)
    			return true;
    		if(o == null)
    			return false;
    		if(! (o instanceof Range))
    			return false;
    		Range r = (Range) o;
    		if(this.starts.equals(r.starts) && this.ends.equals(r.ends))
    			return true;
    		return false;
    	}
    The class is extended by 2 other classes - Gap and Task which does not overrides equals().

    In this example Task equals Gap with the same starts and ends fields... :/.

    What are the solutions (besides overriding equals method in Task and Gap or comparing getClass() (if(! (this.getClass( ).equals(o.getC lass()))) return false) in the Range.equals() method) to avoid it?

    Thanks in advance,
    Etam.
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    There are no alternatives besides (partially) overriding the equals() method in
    the two sub classes or handling it all in the super class equals() method.

    kind regards,

    Jos

    Comment

    • odwrotnie
      New Member
      • Sep 2008
      • 9

      #3
      Originally posted by JosAH
      (...) or handling it all in the super class equals() method (...)
      Do you mean:
      Code:
      if(! (this.getClass().equals(other.getClass())))
       return false;
      ?

      Isn't it ineffective?

      Thanks,
      Pawel.

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by odwrotnie
        Do you mean:
        Code:
        if(! (this.getClass().equals(other.getClass())))
         return false;
        ?

        Isn't it ineffective?

        Thanks,
        Pawel.
        Three method calls; the most expensive (probably) being the equals() method.
        You can't do much better than that in your little three class hierarchy.

        kind regards,

        Jos

        Comment

        Working...