Saturday, May 1, 2010

Java Object model- Equality testing

Some more excerpts from the same book(ObjectorientedDesignPatterns, by Cay Horstmann),
According to Horstmann, the perfect equals method is as below

pulic boolean equals(Object otherObject)
{

if(this==otherObject)
return true; //Many times equals is called on identical objects, then there is no reason

//to check for contents again
if(otherObject==null)//For any non null reference value x, x.equals(null) should return false
return false;

if(getClass()!=otherObject.getClass()//A different Class, obvious
return false;

-
-
-//desired equality conditions to be checked follows...

-
-
-
}

Java Type system

I was reading Object Oriented design Patterns by Cay Horstmann, notes from this book

Java is a strongly typed language. Most type system rules violations are caught during compilation. In other languages like javascript, applying an operation not suiting the value currently stored in the variable will result in a run time error.
Why compile time checking is safer? Run time checks may pass during testing and fail during deployment when un expected values are stored in those type-less variable.

Every type in java can be anyone below

primitive type
class type
interface type
array type
null type


Type Inquiry

instanceof : Tests whether the type of the object is a subtype of the given type.
getClass(): finds the actual type of the object it refers
if e is a Rectangle, e.getClass().getName() is the string, "java.awt.Rectangle"
For an array type, type of array elements is called the component type of the array
When getClass is applied to an array , it returns an array type and not component type.

string[] s=new String[10];
Class class=s.getClass();
if(class.isArray())
S.o.p("Component type"+c.getComponentType());
//will print "Component Type=String"