Home > DeveloperSection > Articles > Object Class in Java

Object Class in Java


Java Java  J2EE 
Ratings:
0 Comment(s)
 828  View(s)
Rate this:



Object Class in Java  



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.
  1. class Student  implements Cloneable{  
  2. int rollno;  
  3. String name;  
  4.   
  5. Student(int rollno,String name){  
  6. this.rollno=rollno;  
  7. this.name=name;  
  8. }  
  9. public Object clone()throws CloneNotSupportedException{  
  10. return super.clone();  
  11. }  
  12. public static void main(String args[]){  
  13. try{  
  14. Student s1=new Student(101,"anupam");  
  15. Student s2=(Student)s1.clone();   
  16. System.out.println(s1.rollno+" "+s1.name);  
  17. System.out.println(s2.rollno+" "+s2.name);  
  18. }catch(CloneNotSupportedException c){}  
  19. }  
  20. }  

Output:      101 anupam 
                      101 anupam


 


Don't want to miss updates? Please click the below button!

Follow MindStick