Java Lang Object PDF
Java Lang Object PDF
java.lang.Object
➢ Object class is defined in java.lang package.
➢ Object class is the super most class for all the classes in java.
➢ In Object class there are 11 non-static methods.
java.lang.Object Page 1
Pg2
Monday, April 27, 2020 8:32 AM
To Override toString() :
purpose:
➢ we override toString() to print state of an object instead of
reference of the object.
java.lang.Object Page 2
for example refer, workspace/object_class/src/pack1/Demo3
Task1 :
java.lang.Object Page 3
Pg3
Tuesday, April 28, 2020 8:13 AM
Example :
class Book
{
String title;
Book(String title) {
this.title = title ;
}
}
java.lang.Object Page 4
refer,
workspace/object_class/pack2/
BookDriver1.java
refer,
workspace/object_class/pack2/
BookDriver2.java
Note:
java.lang.Object Page 5
Pg4
Wednesday, April 29, 2020 8:29 AM
java.lang.Object Page 6
java.lang.Object Page 7
To Override equals(object ) :
java.lang.Object Page 8
To Override equals(object ) :
Purpose: We override equals method to compare the state of two objects instead
of comparing reference of two objects.
design tip : ( in equals method compare the state of current(this) object with
passed object by downcasting it )
Note :
1. if equals method is not overridden it compares the reference of 2 objects
similar to == operator.
2. if equals method is overridden in a class, then it compares the state of
objects and not the reference. in such case if we have to compare the
reference it is possible only with the help of == operator.
Assignment1 :
Assignment2:
java.lang.Object Page 9
Assignment2:
java.lang.Object Page 10
Pg5
Friday, May 1, 2020 8:12 AM
example:
class Mango
{
int price ;
Mango(int price) {
this.price = price ;
}
}
java.lang.Object Page 11
Note :
1. by observing case1 & case2 it is clear that according to java.lang.Object class
implementation of hashCode() and equals() :
example2 :
class Mango
java.lang.Object Page 12
class Mango
{
int price ;
Mango( int price ) {
this.price = price ;
}
// override equals method
java.lang.Object Page 13
Note:
java.lang.Object Page 14
➢ From the above observation it is clear that, if equals() method is overridden, it is
strongly recommended to override hashCode() method also.
➢ If equals() method compares the state of an object, hashCode() should be designed
such that it generates integer based on state of an object.
java.lang.Object Page 15