4/28/2008

details of inheritance in Java

Everyone knows everything is object in Java. sometime if you inherit or create an object, you must keep the general contracts, else you may make bugs. equals(), hashCode(), clone(), finalize(). those are non-final methods, we will discuss below.
  1. Override equals() method is simple, but it will also make mistakes, the best solution is don't override it possibly. if you must override it must keep the below conditions.
    • Reflexive : for all x, x.equals(x) must true.
    • Symmetric : for all x, y, if x.equals(y) is true, then y.equals(x) is true.
    • Transitive : for all x, y, z, if x.equals(y) and y.equals(z) are true, then x.equals(z) is true.
    • Consistent : for all x, y, x.equals(y) == y.equals(x) is forever true.
    • Non nullity : x.equals(null) is false at all time.
  2. hashCode() be override coincide with equals(). if you don't do that, you violate the constracts and can't work normally with HashMap, HashSet, HashTable... If and only if x.equals(y) is true, then x.hashCode() must equal y.hashCode(). sample code: Map m = new HashMap(); m.put(new MyObject("hihi"), "lui"); m.get(new MyObject("hihi")); Usually you believe "m.get(new MyObject("hihi"))" will return the String "lui", but it also return null. it's because the two MyObject is the same in our opinion, but is not the same in program, it has different hashCode, so, for the same object must has the same hashCode.
  3. clone() method is like create a object, you must know clone() is not deep copy, so, it may share member data in two objects, but it isn't you want. So, one solution is don't support clone() method, others is make clone() as like as copy constructor in C++.

沒有留言: