Menu
Topics Index
...
`


Exploring java.lang >
Siva Nookala - 01 Apr 2016
Object is a class in java which is a super class for all other classes in java. When ever you create a class it will become a sub class for the Object class. So every class can extend the methods in Object.

Methods of a Object class :
Method Description
protected Object clone() throws CloneNotSupportedException Creates and returns a copy of this object.
public boolean equals(Object obj) Indicates whether some other object is "equal to" this one.
protected void finalize() throws Throwable Called by the garbage collector on an object when garbage collection determines that there are no more references to the object
public final Class getClass() Returns the runtime class of an object.
public int hashCode() Returns a hash code value for the object.
public String toString() Returns a string representation of the object.
using clone method of Object class
class ObjectDemo implements Cloneable // LINE A
{
    public static void main(String[] args) throws CloneNotSupportedException
    {
        ObjectDemo obj1 = new ObjectDemo();
        ObjectDemo obj2 = (ObjectDemo)obj1.clone(); // LINE B
        if(obj1.equals(obj2))
            System.out.println("obj1 equals to obj2");
        else
            System.out.println("obj1 not equals to obj2");
    }
}
OUTPUT

obj1 not equals to obj2

DESCRIPTION

In the above program we used the methods of Object class. Normally if the class object which is invoking clone() method don't implement the Cloneable interface JVM will throw CloneNotSupportedException. So at LINE A in our ObjectDemo program implements the Cloneable. Here we don't need to provide the body for the clone() method because super class has it's implementation for it so when we say obj1.clone() it will call the Object class method. Also see at LINE B we typecasted to ObjectDemo because the return type of clone() is Object so we need to typecast it to ObjectDemo.

THINGS TO TRY
  • Now see what if our class don't implement the Cloneable. The method clone() will throw CloneNotSupportedException
  • Also see what happens if don't do the typecasting at LINE B
  • To find the class name any object we need to do as follows.
    Syntax :
    object.getClass().getSimpleName()
    now find and print the class name of obj1.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.