articles

Home / DeveloperSection / Articles / Object Class in Java

Object Class in Java

Anupam Mishra3777 09-Nov-2015

The Object class is useful  if you want to refer any object whose type you don't know. Note that parent class reference variable can refer the child class object, know as upcasting.

Now ,we taken an example, there is getObject() method that returns an object but it can be of any type like Employee,Student etc, we can use Object class reference to refer that object. For example:

Object obj=getObject();//we don't what object would be returned from this method

The Object class provides some common behaviours to all the objects such as object can be compared, object can be cloned, object can be notified etc. 


For Example:    Object Cloning


The object cloning is used to create exact copy of an object. 

For this purpose, clone() method of Object class is used to clone an object. The clone() method saves the extra processing task for creating the exact copy of an object.

class Student  implements Cloneable{  
int rollno;  
String name;    
Student(int rollno,String name){  
this.rollno=rollno;  
this.name=name;  
}  
public Object clone()throws CloneNotSupportedException{  
return super.clone();  
}  
public static void main(String args[]){  
try{  
Student s1=new Student(101,"anupam");  
Student s2=(Student)s1.clone();   
System.out.println(s1.rollno+" "+s1.name);  
System.out.println(s2.rollno+" "+s2.name);  
}catch(CloneNotSupportedException c){}  
}  
}  


                                Output:      101 anupam 
                                                      101 anupam



                                 


                                java java  j2ee 
                                Updated 14-Dec-2017

                                Leave Comment

                                Comments

                                Liked By