This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Any object which IS-ALine can pass the instanceoftest in line 1. Any obect of the following class Rectangle will pass the instanceof test in line 1.
Now if a Rectangle object has the same Length(Instance Variable) as a Line object, the second euality test in line 1 will evaluate true, hence true is returned from the equals() method of a Line object.
Hence, a Line object with length 3 is same as a Rectangle object with length 3 and breadth 2.
I don't know what Object Orientation says. But, whatever does it say, is it correct?
I want two different objects evaluates false in equals() method, anyhow, without using Generics or any higher order supporting stuff.
I am trying. Please somebody help..................... [ August 14, 2008: Message edited by: ARIJIT DARIPA ]
Don't forget to override hashCode as well! Read the API of Object to see why.
This code still has one flaw though - it violates one rule of the Object.equals contract: it's not symmetric.
Consider the following:
This is why I almost always code my equals methods as follows:
I only use instanceof if one of the following occurs:
The class is final. There can be no subclass, so only objects of the class itself will pass the instanceof test
The equals method is final. Since it can't be overridden, subclasses cannot use their own instanceof.
I do have one question about your design though. Is a Rectangle really a Line? It can be, but not the way you have represented it. With your definition of length and breadth, a Rectangle has Lines, but it isn't one. Now a Rectangle can be a line (with corners), but then length will be the 4 sides added, and not just the length of one size.