Sobes.tech
Junior

What is the role of the Object class in Java?

sobes.tech AI

Answer from AI

The Object class is the root class of the class hierarchy in Java. It is the superclass of all other classes, including arrays.

Main roles and functions:

  • Common ancestor: Every class in Java implicitly inherits from Object. This means that any object in Java can be cast to the Object type.
  • Providing a basic set of methods: Object contains a set of fundamental methods available to all objects. These include:
    • equals(Object obj): Compares two objects for equality.
    • hashCode(): Returns the hash code of the object.
    • toString(): Returns a string representation of the object.
    • getClass(): Returns the Class object representing the runtime class of the object.
    • notify(), notifyAll(), wait(), wait(long timeout), wait(long timeout, int nanos): Methods used for thread synchronization.
    • clone(): Creates and returns a copy of the object (requires implementation of the Cloneable interface).
    • finalize(): Method called by the garbage collector before the object is removed (deprecated, not recommended for use).
  • Polymorphism: Because Object is a common ancestor, you can create collections or methods that can work with any object type, leveraging polymorphism. For example, ArrayList<Object> can store elements of any type.
// Example of using the toString() method
public class MyClass {
    private int value;

    public MyClass(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "MyClass [value=" + value + "]";
    }

    public static void main(String[] args) {
        MyClass obj = new MyClass(10);
        System.out.println(obj.toString()); // Outputs "MyClass [value=10]"
    }
}
What is the role of the Object class in Java? — Java - sobes.tech