Object class

Java is a class-based, object-oriented programming language, and at the root of its class hierarchy is the Object class. This class is the superclass of all classes in Java, meaning every class implicitly inherits from the Object class unless it explicitly extends another class. The Object class is part of the java.lang package and provides several essential methods that are fundamental to Java programming.

Importance of the Object Class

  1. Root of the Class Hierarchy: Every class in Java is a direct or indirect subclass of Object. This ensures that every object in Java can be treated as an instance of Object and can utilize the methods defined in the Object class.

  2. Universal Superclass: It provides common functionalities to all Java objects, allowing them to be compared, cloned, notified, and garbage collected.

  3. Polymorphism and Inheritance: Methods in the Object class can be overridden to provide class-specific implementations, thus supporting polymorphism and inheritance.

Methods of the Object Class

The Object class provides several crucial methods. Let’s explore each method in detail:

  1. toString() Method:
  • Returns a string representation of the object.
  • Default implementation: Class name followed by the @ symbol and the hashcode in hexadecimal format.
  • Syntax:
public String toString()Code language: JavaScript (javascript)

Example

public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{name='" + name + "', age=" + age + "}";
    }
}

public class Main {
    public static void main(String[] args) {
        Student student = new Student("Mahesh", 25);
        System.out.println(student.toString());
    }
}Code language: JavaScript (javascript)

2. equals(Object obj) Method:

  • Compares the current object with the specified object.
  • Default implementation: Compares memory addresses.
  • Syntax:
public boolean equals(Object obj)Code language: JavaScript (javascript)

Example

@Override
public boolean equals(Object obj) {
    if (this == obj) return true;
    if (obj == null || getClass() != obj.getClass()) return false;
    Student student = (Student) obj;
    return age == student.age && name.equals(student.name);
}Code language: JavaScript (javascript)

3. hashCode() Method:

  • Returns an integer hash code for the object.
  • It is used in hash-based collections like HashMap, HashSet, etc.
  • Syntax:
public int hashCode()Code language: PHP (php)

4. getClass() Method:

  • Returns the runtime class of the object.
  • Syntax:
public final Class<?> getClass()Code language: HTML, XML (xml)

Example

public class Main {
    public static void main(String[] args) {
        Student student = new Student("Mahesh", 25);
        System.out.println(student.getClass().getName());
    }
}Code language: JavaScript (javascript)

5. clone() Method:

  • Creates and returns a copy of the object.
  • The class must implement the Cloneable interface.
  • Syntax:
protected Object clone() throws CloneNotSupportedExceptionCode language: PHP (php)

Example

@Override
protected Object clone() throws CloneNotSupportedException {
    return super.clone();
}Code language: PHP (php)

6. notify() and notifyAll() Methods:

  • Wakes up threads that are waiting on the object’s monitor.
  • Syntax
public final void notify()
//Wakes up one thread that is currently waiting on the monitor (lock) of the object.
public final void notifyAll()
//Wakes up all threads that are currently waiting on the monitor (lock) of the object.Code language: PHP (php)

7. wait() Method:

  • Causes the current thread to wait until another thread invokes notify() or notifyAll().
  • Syntax:
public final void wait() throws InterruptedExceptionCode language: PHP (php)

Example: Demonstrating the Object Class Methods

public class Employee implements Cloneable {
    private String name;
    private int id;

    public Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }

    @Override
    public String toString() {
        return "Employee{name='" + name + "', id=" + id + "}";
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Employee employee = (Employee) obj;
        return id == employee.id && name.equals(employee.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, id);
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        Employee e1 = new Employee("LotusJavaPrince", 101);
        Employee e2 = new Employee("Mahesh", 102);
        Employee e3 = (Employee) e1.clone();

        System.out.println("e1.toString(): " + e1.toString());
        System.out.println("e1.equals(e2): " + e1.equals(e2));
        System.out.println("e1.equals(e3): " + e1.equals(e3));
        System.out.println("e1.hashCode(): " + e1.hashCode());
        System.out.println("e3.hashCode(): " + e3.hashCode());
    }
}
/*
e1.toString(): Employee{name='LotusJavaPrince', id=101}
e1.equals(e2): false
e1.equals(e3): true
e1.hashCode(): 1682211537  
e3.hashCode(): 1682211537  
*/

The Object class in Java serves as the superclass for all other classes and provides essential methods that every Java object can utilize. Methods like equals(), hashCode(), toString(), clone(), getClass(), wait(), notify(), and notifyAll() define fundamental behaviors such as comparison, hashing, string representation, and object synchronization. By overriding these methods, developers can tailor the functionality of their classes to meet specific requirements while maintaining consistency across Java objects.

Understanding the Object class is crucial for mastering Java inheritance, as it provides a foundational set of methods that can be leveraged in any class hierarchy. Additionally, its getClass() method is integral for implementing reflection, allowing developers to inspect object structure at runtime.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top