Object Class

In this chapter you will learn:

  1. How is Java root class it defined
  2. How to use clone( ) and the Cloneable Interface

Get to know Object class

Object is a superclass of all other classes. Therefore, Object can refer to an object of any other class. Also, a variable of type Object can also refer to any array.

Object defines the following methods, which means that they are available in every object. The following table lists methods from object class.

ReturnMethod Purpose
Objectclone() Creates a new object that is the same as the object being cloned.
booleanequals(Object object) Determines whether one object is equal to another.
voidfinalize() Called before an unused object is recycled.
ClassgetClass() Obtains the class of an object at run time.
inthashCode() Returns the hash code associated with the invoking object.
voidnotify() Resumes execution of a thread waiting on the invoking object.
voidnotifyAll() Resumes execution of all threads waiting on the invoking object.
StringtoString() Returns a string that describes the object.
voidwait() Waits on another thread of execution.
voidwait(long milliseconds) Waits on another thread of execution.
voidwait(long milliseconds, int nanoseconds)Waits on another thread of execution.

getClass(), notify(), notifyAll(), and wait() are final.

The equals() method compares the contents of two objects. It returns true if the objects are equivalent, and false otherwise.

The toString() method returns a string that contains a description of the object. toString() method is automatically called when an object is output using println().

clone() and the Cloneable Interface

The clone() method generates a duplicate copy of the object. Only classes that implement the Cloneable interface can be cloned. If you try to call clone() on a class that does not implement Cloneable, a CloneNotSupportedException is thrown.

clone() is declared as protected inside Object. Let's look at an example of each approach. The following program implements Cloneable and defines the method cloneTest(), which calls clone() in Object:

class TestClone implements Cloneable {
  int a;/* jav  a2s  .  com*/
  public Object clone() {
    try {
      return super.clone();
    } catch (CloneNotSupportedException e) {
      System.out.println("Cloning not allowed.");
      return this;
    }
  }
}
public class Main {
  public static void main(String args[]) {
    TestClone x1 = new TestClone();
    TestClone x2;
    x1.a = 10;
    // here, clone() is called directly.
    x2 = (TestClone) x1.clone();
    System.out.println("x1: " + x1.a);
    System.out.println("x2: " + x2.a);
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. What is Java package
  2. How to define a Java package
  3. How to create a hierarchy of packages
  4. How to map Java package to directory