Java.Core.What is the Object class? What methods does it have?

The Object class is the root class of all Java classes. Every class in Java implicitly inherits from Object, either directly or indirectly.

📌 Key Facts About Object Class:

  • It is part of the java.lang package.
  • It provides basic methods that every Java object can use.
  • If a class does not explicitly extend another class, it automatically extends Object.

Methods of the Object Class

The Object class provides several important methods that are inherited by all Java classes.

1. equals(Object obj)

  • Compares the current object with another object for equality.
  • Default behavior: Compares memory addresses (reference comparison).
  • Override this method to perform content comparison.

Example: Default equals() (Reference Comparison)

public class EqualsExample {
    public static void main(String[] args) {
        Object obj1 = new Object();
        Object obj2 = new Object();

        System.out.println(obj1.equals(obj2)); // false (Different objects)
    }
}

Example: Overriding equals() (Content Comparison)

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }

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

public class EqualsOverride {
    public static void main(String[] args) {
        Person p1 = new Person("Alice");
        Person p2 = new Person("Alice");

        System.out.println(p1.equals(p2)); // true (Same content)
    }
}

2. hashCode()

  • Returns an integer hash code for an object.
  • The default implementation returns a unique integer for each object (memory reference-based).
  • Must be overridden when equals() is overridden, to maintain consistency.

Example: Default hashCode()

public class HashCodeExample {
    public static void main(String[] args) {
        Object obj = new Object();
        System.out.println(obj.hashCode()); // Example output: 12345678
    }
}

Example: Overriding hashCode()

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }

    @Override
    public int hashCode() {
        return name.hashCode(); // Uses the hash of the name
    }
}

🔹 Best Practice: If two objects are “equal” (equals() returns true), they must have the same hashCode().


3. toString()

  • Returns a string representation of the object.
  • Default behavior: Returns "ClassName@hashcode" (not very useful).
  • Override this method to provide a meaningful string representation.

Example: Default toString()

public class ToStringExample {
    public static void main(String[] args) {
        Object obj = new Object();
        System.out.println(obj.toString()); // Output: java.lang.Object@5a07e868
    }
}

Example: Overriding toString()

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }

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

public class ToStringOverride {
    public static void main(String[] args) {
        Person p = new Person("Alice");
        System.out.println(p); // Output: Person{name='Alice'}
    }
}

🔹 Best Practice: Always override toString() to make debugging easier.


4. getClass()

  • Returns the runtime class of an object.

Example: Using getClass()

public class GetClassExample {
    public static void main(String[] args) {
        String str = "Hello";
        System.out.println(str.getClass()); // Output: class java.lang.String
    }
}

5. clone()

  • Creates a shallow copy of the object.
  • Default implementation: Performs a bitwise copy.
  • Requires the class to implement Cloneable interface, otherwise CloneNotSupportedException is thrown.

Example: Cloning an Object

class Person implements Cloneable {
    String name;

    Person(String name) {
        this.name = name;
    }

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

public class CloneExample {
    public static void main(String[] args) throws CloneNotSupportedException {
        Person p1 = new Person("Alice");
        Person p2 = (Person) p1.clone();

        System.out.println(p1.name); // Alice
        System.out.println(p2.name); // Alice
    }
}

🔹 Best Practice: Implement deep cloning if objects have references to other objects.


6. finalize() (Deprecated in Java 9)

  • Called before an object is garbage collected.
  • Not recommended because garbage collection is unpredictable.

Example: finalize() Method

class Resource {
    @Override
    protected void finalize() throws Throwable {
        System.out.println("Object is being garbage collected");
    }
}

public class FinalizeExample {
    public static void main(String[] args) {
        Resource r = new Resource();
        r = null;
        System.gc(); // Request garbage collection
    }
}

🔹 Best Practice: Use try-with-resources instead of finalize() for resource cleanup.


7. wait(), notify(), and notifyAll()

These methods are used for thread synchronization in multithreading.

MethodDescription
wait()Makes the current thread wait until notified.
notify()Wakes up one waiting thread.
notifyAll()Wakes up all waiting threads.

Example: Using wait() and notify()

class SharedResource {
    synchronized void waitForSignal() throws InterruptedException {
        System.out.println("Waiting...");
        wait();
        System.out.println("Got signal!");
    }

    synchronized void sendSignal() {
        notify();
        System.out.println("Signal sent!");
    }
}

public class WaitNotifyExample {
    public static void main(String[] args) {
        SharedResource resource = new SharedResource();

        new Thread(() -> {
            try { resource.waitForSignal(); } catch (InterruptedException e) { }
        }).start();

        new Thread(() -> {
            try { Thread.sleep(1000); resource.sendSignal(); } catch (InterruptedException e) { }
        }).start();
    }
}

Benefit: Used for inter-thread communication.


Summary: Methods in Object Class

MethodDescriptionOverride Needed?
equals(Object obj)Compares objects✅ Yes (for content comparison)
hashCode()Returns hash code✅ Yes (when equals() is overridden)
toString()String representation of object✅ Yes (for readability)
getClass()Returns the runtime class❌ No
clone()Creates a copy of the object✅ Yes (if cloning is needed)
finalize()Called before garbage collection❌ No (deprecated)
wait(), notify(), notifyAll()Used for thread synchronization❌ No

Conclusion

  • Object is the parent class of all Java classes.
  • Overriding equals(), hashCode(), and toString() is a best practice.
  • Methods like clone(), wait(), and notify() are used in advanced cases.
This entry was posted in Без рубрики. Bookmark the permalink.