What are the methods of Object class in Java?

0
6
methods of Object

In Java, the Object class is the superclass of all classes in the Java programming language. Every class in Java is directly or indirectly derived from the Object class.

The Object class provides several methods that can be overridden by subclasses, such as:

  • toString(): returns a string representation of the object
  • equals(): compares the given object with the current object for equality
  • hashCode(): returns a hash code value for the object
  • clone(): creates and returns a copy of the object
  • finalize(): called by the garbage collector when there are no more references to the object
  • getClass(): returns the runtime class of an object
  • wait(): causes the current thread to wait until another thread invokes the notify() or notifyAll() method

It also defines a default behavior for these methods, which can be overridden by subclasses to provide more specific behavior.

Additionally, it serves as a base class for many of the classes in the Java API and provides a common set of methods that can be used on any object, regardless of its specific type.

ToString() method in object class

The toString() method in the Object class is a method that returns a string representation of the object. The default implementation of this method in the Object class returns a string consisting of the name of the class of the object, an “@” symbol, and the hexadecimal representation of the hash code of the object. For example, if an object of the class “MyClass” has a hash code of 0x12345, the default toString() method would return the string “MyClass@12345”.

However, it is often useful to override this method in subclasses to provide more meaningful string representations of the objects. This can be done by including information such as the state of the object, its properties, or other relevant data.

For example, the following code defines a simple class, “Person”, with a name and age property, and overrides the toString() method to return a string containing the name and age of the person:

class Person {
  private String name;
  private int age;
  
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
  
  @Override
  public String toString() {
    return "Name: " + name + ", Age: " + age;
  }
}

It is important to note that the toString() method should be designed to return a string representation of the object that is suitable for the intended use case. It should be designed to be human-readable, and should not include sensitive data like passwords.

Also, the toString() method is often used by various framework and libraries. For example, when using an object in a print statement, the toString() method is automatically called to get the string representation of the object.

equals() method in object class

The equals() method in the Object class is a method that compares the given object with the current object for equality. The default implementation of this method in the Object class compares the memory addresses of the two objects to determine if they are the same. This means that two different objects, even if they have the same properties and values, will not be considered equal by the default implementation of the equals() method.

However, it is often useful to override this method in subclasses to provide a more meaningful comparison of objects. This can be done by including information such as the state of the object, its properties, or other relevant data.

For example, the following code defines a simple class, “Person”, with a name and age property, and overrides the equals() method to compare the name and age of two persons:

class Person {
  private String name;
  private int age;
  
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
  
  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (!(obj instanceof Person)) {
      return false;
    }
    Person p = (Person) obj;
    return p.name.equals(name) && p.age == age;
  }
}

It is important to note that when overriding the equals() method, it is also a good practice to override the hashCode() method so that it returns the same value for two objects that are considered equal by the equals() method. Also, it is recommended to follow the contract of equals method which defined by the class java.lang.Object and include a check for the same object using if(obj == this) and also check the type of obj using if(!(obj instanceof Person)) before casting it to the target class and comparing the properties.

It is worth noting that the equals() method should be designed to return a true only if the two objects are considered to be the same. It should be reflexive, symmetric, transitive and consistent.

hashCode() method in object class

The hashCode() method in the Object class is a method that returns a hash code value for the object. A hash code is a numerical value that is used to identify an object in a data structure such as a HashMap or HashSet. The default implementation of this method in the Object class returns a hash code that is based on the memory address of the object, which means that two different objects, even if they have the same properties and values, will have different hash codes by default.

However, it is often useful to override this method in subclasses to provide a more meaningful hash code for the object. This can be done by including information such as the state of the object, its properties, or other relevant data.

For example, the following code defines a simple class, “Person”, with a name and age property, and overrides the hashCode() method to include the name and age of the person in the hash code calculation:

class Person {
  private String name;
  private int age;
  
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
  
  @Override
  public int hashCode() {
    return Objects.hash(name, age);
  }
}

It is important to note that when overriding the hashCode() method, it should return the same value for two objects that are considered equal by the equals() method. This is because hash-based data structures like HashMap and HashSet use the hash code to determine where to store or look for an object, and if two objects that are considered equal have different hash codes, they may be stored in different locations and not be found when looking for them.

It is also worth noting that, it’s recommended to use utility classes like java.util.Objects to generate the hash code because it will handle the null values and also it’s a good practice to use multiple fields in the calculation of the hash code, by using a prime number for each field to produce a unique hash code.

clone() method in object class

The clone() method in the Object class is a method that creates and returns a copy of the object. The default implementation of this method in the Object class performs a shallow copy of the object, meaning that it only copies the references to the object’s fields, rather than creating new copies of the fields themselves.

However, it is often useful to override this method in subclasses to perform a deep copy of the object. A deep copy creates new copies of the object’s fields, rather than copying references to the fields. This allows the cloned object to be modified without affecting the original object.

For example, the following code defines a simple class, “Person”, with a name and age property, and overrides the clone() method to perform a deep copy of the object:

class Person implements Cloneable {
  private String name;
  private int age;
  
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
  
  @Override
  public Person clone() throws CloneNotSupportedException {
    return new Person(name, age);
  }
}

It’s important to note that the clone() method is protected in the Object class, which means that it can only be called on an object within the same package as the object. To allow the clone() method to be called on an object from other packages, the class must implement the Cloneable interface, which is a marker interface that indicates that the class is cloneable.

Also, it’s worth noting that, while it’s easy to implement, it’s not always the best option to use the clone method, because it has some drawbacks like it will not work with the classes that have circular references, also it’s not guaranteed that the cloned object will have the same state as the original object, because it’s possible to have a class that has some mutable fields, and in this case the cloned object will have the same references to these fields which means that if you modify this field in the cloned object, it will affect the original object as well.

finalize() method in object class

The finalize() method in the Object class is a method that is called by the garbage collector when it determines that there are no more references to the object. This method can be overridden by subclasses to perform any cleanup that is necessary before the object is collected by the garbage collector.

For example, a class that opens a file or a database connection might override the finalize() method to close the file or connection before the object is collected.

class MyResource implements AutoCloseable {
    private File file;
    public MyResource(File f) {
        this.file = f;
    }
    public void read() {
        // read from file
    }
    public void close() {
        // close the file
    }
    @Override
    protected void finalize() throws Throwable {
        try {
            close();
        } finally {
            super.finalize();
        }
    }
}

It’s important to note that the finalize() method is not guaranteed to be called. The garbage collector runs periodically and decides when to collect objects based on the available memory and the number of references to the objects. Additionally, the finalize() method is run by a special thread called the “finalizer thread”, which means that it might take some time before the finalize() method is called and it might not be called at all if the program exits before the finalizer thread has a chance to run.

Also, it’s worth noting that, the finalize method is considered as a deprecated method since Java 9. It’s recommended to use try-with-resources statement or AutoCloseable interface along with the close method to handle the resources clean up.

The finalize() method is a low-level mechanism that is intended for use by the Java Virtual Machine (JVM) and should be used with caution. It’s recommended to avoid using it if possible, because it’s not guaranteed to be called and also it’s not guaranteed to be called in a timely manner.

getClass() method in object class

The getClass() method in the Object class is a method that returns the runtime class of an object. The class returned by this method is an instance of the Class class, which contains information about the object’s class such as the class name, methods, fields, and other properties.

For example, the following code creates an instance of the String class and uses the getClass() method to get information about the class:

String str = "Hello";
Class c = str.getClass();
System.out.println(c.getName()); // prints "java.lang.String"

The getClass() method can be useful for determining the type of an object at runtime, which can be useful for implementing type-specific behavior or for logging and debugging.

It’s also worth noting that, the getClass() method returns the class of the object at runtime, which means that if the object is an instance of a subclass, it will return the class of the subclass, not the class of the superclass.

class A {
    // ...
}
class B extends A {
    // ...
}

A a = new B();
System.out.println(a.getClass().getName()); // prints "B"

Additionally, the class returned by the getClass() method provides several methods that can be used to get information about the class, such as getName(), which returns the fully-qualified name of the class, and getMethods(), which returns an array of Method objects representing the methods of the class.

wait() method in object class

The wait() method in the Object class is a method that causes the current thread to wait until another thread invokes the notify() or notifyAll() method on the object. The wait() method is used for inter-thread communication and is a core feature of the Java language for synchronizing the execution of multiple threads.

When a thread calls the wait() method, it releases the lock on the object and goes into a waiting state. Other threads can then acquire the lock on the object and make changes to its state. When another thread calls the notify() or notifyAll() method on the object, the waiting thread wakes up and re-acquires the lock on the object.

For example, the following code defines a simple class, “Buffer”, which represents a buffer that can be filled and emptied by two different threads. The fill() method acquires a lock on the buffer, fills it with data, and then calls the notify() method to wake up any threads that are waiting on the buffer:

class Buffer {
    private int[] data;
    private int size = 0;
    public Buffer(int capacity) {
        data = new int[capacity];
    }
    public synchronized void fill(int value) {
        while (size == data.length) {
            try {
                wait();
            } catch (InterruptedException e) {
                // handle interruption
            }
        }
        data[size++] = value;
        notify();
    }
    public synchronized int get() {
        while (size == 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                // handle interruption
            }
        }
        int result = data[--size];
        notify();
        return result;
    }
}

It’s important to note that the wait() method should be called inside a synchronized block, because it releases the lock on the object and a thread must hold the lock on an object to call the wait() method. Additionally, the wait() method can throw an InterruptedException, which should be handled by the calling thread.

Also, the wait() method has overloaded versions that take a timeout value, which causes the thread to wait for the specified amount of time before waking up. It’s important to note that, the wait method should be called

LEAVE A REPLY

Please enter your comment!
Please enter your name here