Friday, October 29, 2010

instanceof OR getClass()

First, wanna share a nice vim/gvim theme called Wombat. Just download it and put it into $HOME/.vim/colors and setcolors wombat in your $HOME/.vimrc and .gvimrc.



I have seen several interview questions asking you to override equals() method for your class. There are two ways to check the classname. Take a Foo class for example:

public class Foo{
private int id;
public boolean equals(Object o){
if (this == o)
return true;
if (!(o instanceof Foo))
return false;
if (o == null)
return false;
Foo other = (Foo)o;
return (this.id == other.id) ? true : false;
}



Another way:

public class Foo{
private int id;
public boolean equals(Object o){
if (this == o)
return true;
if (getClass() != o.getClass())
return false;
if (o == null)
return false;
Foo other = (Foo)o;
return (this.id == other.id) ? true : false;
}



Basically, it is a question of using instanceof or getClass(). Josh Bloch in his Effective Java and his interview with Altima argues that instanceof should be used because of Liskov substitution principle, meaning that one subclass object should be able to replace occurrences of its superclass object without making changes for correctness.



Cay Horstmann does not agree with the use of instanceof and argues that getClass() method should be used instead to enforce the contract of equals method. He presents a superclass-subclass example where reflexive contract for equals method is broken: parent.equals(child) is true, but child.equals(parent) is false if we stick to the instanceof approach.



I think with some special conditional checks on the inheritance structure, you can still use instanceof and satisfy reflexive contract. But getClass() is much simpler.



So, basically, the question is like this: if Eric is a manager, he is represented as an object e of Employee class and an object m of Manager class which extends Employee class. Do you think e equals m (because they are actually representing a same person, using instanceof approach) or do you think they are not equals (because they are of different classes, using getClass() approach)?

No comments:

Post a Comment