Object Class
Object Class
Object class :
● Object class is defined in java.lang package.
● Object class is a supermost parent class for all the classes in java.
● In object class there are 11 non static methods.
● One no argument constructor is there.
public String toString()
NOTE :
● If equals(Object ) method is not overridden it compares the reference of two
objects similar to == operator.
● If equals(Object) method is overridden it compares the state of two objects,
in such case comparing the reference of two objects is possible only by ==
operator.
Design tip :
In equals method compare the state of an current(this) object with the passed
object by downcasting the passed object.
EXAMPLE :
class Book
{
String bname ;
Book(String bname)
{
this.bname = bname ;
}
@Override
public boolean equals(Object o)
{
Book b = (Book)o;
if(this.bname.equals(b.bname))
return true;
else
return false;
}
}
hashCode() :
● The return type of hashCode() method is int.
● The java.lang.Object implementation of hashCode() method is used to
give the unique integer number for every object created.
● The unique number generated based on the reference of an object.
PURPOSE OF OVERRIDING hashCode() :
If the equals(Object) method is overridden , then it is necessary to override
the hashCode() method.
Design tip :
hashCode() method should return an integer number based on the state of an
object.
EXAMPLE 1:
class Pen
{
double price ;
Pen(double price)
{
this.price = price ;
}
@Override
public int hashCode()
{
int hc = (int)price;
return hc ;
}
}
class Book
{
int bid ;
double price ;
Book(int bid , double price)
{
this.bid = bid ;
this.price = price;
}
@Override
public int hashCode()
{
int hc1 = bid ;
double hc2 = price ;
int hc = hc1+(int)hc2;
return hc ;
}
}
EXAMPLE 1 :
class Book
{
String bname;
Book(String bname)
{
this.bname = bname;
}
}
In the above two cases it is clear that,
● If the hashcode for two object is same, equals(Object) method will
return true.
● If the hashcode for two object is different, equals(Object) method will
return false.