java - overriding equals method when dealing with inheritance -


i have been reading how best override equals method when dealing subclasses , here have found quite few posts. recommend different ways of implementing solution using instanceof or getclass() compare objects of different sub classes.

however reference effective java, understanding (and new may wrong!) bloch argues in end both can problematic, “there no way extend instantiable class , add value component while preserving equals contract, unless willing forgo benefits of object-oriented abstraction”. recommends “favour composition on inheritance”.

so dealing class hierarchy: abstractclass, concreteclass1 , concreteclass2. concreteclass1 extends abstractclass , concreteclass2 extends concreteclass1. @ moment abstractclass overrides equals method.

so in abstractclass:

public abstract class abstractclass {         private string id;           public boolean equals(object other) {             return other != null && other.getclass().equals(getclass())                     && id.equals(((abstractclass) other).id);         }      } 

and in concreteclass1 have:

public class concreteclassone extends abstractclass {   private final abstractclass parent;    public concreteclassone( string anid, abstractclass aparent )   {     super( anid );      parent = aparent;   }  } 

finally in concreteclasstwo have:

public class concreteclasstwo extends concreteclassone {   private static int nexttrackingno = 0;    private final int trackingno;    public concreteclasstwo ( string anid )   {     super( anid, null );      trackingno= getnexttrackingno();   } } 

so believe need override equals method in both concreteclassone , concreteclasstwo include significant fields parent , trackingno. i'm not allowed change design using composition not option. suggestions?

the simplest approach extend equals() in both concrete , abstract classes.

public class concreteclasstwo extends concreteclassone {     public boolean equals(object other) {         boolean rv = super.equals( other );         if ( other instanceof concreteclasstwo ) {            rv = rv && (this.trackingno == ((concreteclasstwo) other).trackingno);         }         return rv;     } } 

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -