9.6 The Object Class

There is one special class, Object, defined by Java. All other classes are subclasses of Object. That is, Object is a super class of all other classes. This means that a reference variable of type Object can refer to an object of any other class.

Object defines the following methods, which means that they are available in every object.

Method Purpose
public Object() Constructor
public String toString() Method to return a string to describe the object
public boolean equals(Object obj) Method to determine if two objects are the same. Returns true if the object invoking the method and the object specified by the parameter obj refer to the same memory space otherwise it returns false.
protected Object clone() Method to return a reference to a copy of the object invoking this method
protected void finalize() The body of this method is invoked when the object goes out of scope.


Program (Rectangle.java)

public class Rectangle
private double length;
private double width;

public Rectangle(double length, double width)
this.length = length;
this.width = width;

Program (ObjectMethod.java)

 *  This program demonstrates the equals 
 *  methods that is inherited from the Object class. 
public class ObjectMethod
   public static void main(String[] args)
      // Create two objects.
      Rectangle rectangle1 = new Rectangle(12, 15);
      Rectangle rectangle2 = new Rectangle(12, 15);

      // Test the equals method.
      if (rectangle1.equals(rectangle2))
         System.out.println("The two are the same.");
         System.out.println("The two are not the same.");

Output :

The two are not the same.

If you wish to change the behavior of either of these methods for a given class, you must override them in the class.