Object Class Methods in Java with Examples

The Object class in the java.lang package is the root of the class hierarchy. Every class in Java inherits from this class, either directly or indirectly. This means every class has access to the methods provided by the Object class. Understanding these methods is fundamental to mastering Java.

Object Class Methods

Here are the methods we will cover:

  1. protected Object clone()
  2. boolean equals(Object obj)
  3. protected void finalize()
  4. Class<?> getClass()
  5. int hashCode()
  6. void notify()
  7. void notifyAll()
  8. void wait()
  9. String toString()

1. protected Object clone()

The clone() method creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that for any object x, the expression x.clone() != x will be true, and that the expression x.clone().getClass() == x.getClass() will also be true.

Example

class Person implements Cloneable {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

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

    @Override
    public String toString() {
        return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        Person person1 = new Person();
        person1.setFirstName("Ramesh");
        person1.setLastName("Fadatare");

        Person person2 = (Person) person1.clone();

        System.out.println(person1);
        System.out.println(person2);
    }
}

Output:

Person [firstName=Ramesh, lastName=Fadatare]
Person [firstName=Ramesh, lastName=Fadatare]

2. boolean equals(Object obj)

The equals(Object obj) method indicates whether some other object is "equal to" this one.

Example

class Person {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (firstName == null) {
            if (other.firstName != null)
                return false;
        } else if (!firstName.equals(other.firstName))
            return false;
        if (lastName == null) {
            if (other.lastName != null)
                return false;
        } else if (!lastName.equals(other.lastName))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
    }

    public static void main(String[] args) {
        Person person1 = new Person();
        person1.setFirstName("Ramesh");
        person1.setLastName("Fadatare");

        Person person2 = new Person();
        person2.setFirstName("Ramesh");
        person2.setLastName("Fadatare");

        System.out.println(person1.equals(person2));
    }
}

Output:

true

3. protected void finalize() - deprecated

The finalize() method is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Example

class Person {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

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

    @Override
    public String toString() {
        return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.setFirstName("Ramesh");
        person.setLastName("Fadatare");

        person = null;

        System.gc(); // Requesting JVM to run Garbage Collector
    }
}

Output:

Person object is being garbage collected

4. Class<?> getClass()

The getClass() method returns the runtime class of an object.

Example

class Person {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public static void main(String[] args) {
        Person person = new Person();
        System.out.println(person.getClass());
    }
}

Output:

class Person

5. int hashCode()

The hashCode() method returns a hash code value for the object.

Example

class Person {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
        result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
        return result;
    }

    public static void main(String[] args) {
        Person person1 = new Person();
        person1.setFirstName("Ramesh");
        person1.setLastName("Fadatare");

        Person person2 = new Person();
        person2.setFirstName("Ramesh");
        person2.setLastName("Fadatare");

        System.out.println(person1.hashCode());
        System.out.println(person2.hashCode());
    }
}

Output:

-1066062211
-1066062211

6. void notify(), 7. void notifyAll(), and 8. void wait()

These methods are used for thread synchronization.

Example

import java.util.LinkedList;
import java.util.List;

class ObjectClassNotifyNotifyAllAndWaitExample {
    private final List<String> synchedList = new LinkedList<>();

    public String removeElement() throws InterruptedException {
        synchronized (synchedList) {
            while (synchedList.isEmpty()) {
                System.out.println("List is empty...");
                synchedList.wait();
                System.out.println("Waiting...");
            }
            return synchedList.remove(0);
        }
    }

    public void addElement(String element) {
        System.out.println("Opening...");
        synchronized (synchedList) {
            synchedList.add(element);
            System.out.println("New Element added: '" + element + "'");
            synchedList.notifyAll();
            System.out.println("notifyAll called!");
        }
        System.out.println("Closing in AddElement method...");
    }

    public static void main(String[] args) {
        final ObjectClassNotifyNotifyAllAndWaitExample demo = new ObjectClassNotifyNotifyAllAndWaitExample();

        Runnable runA = () -> {
            try {
                String item = demo.removeElement();
                System.out.println("" + item);
            } catch (InterruptedException ix) {
                System.out.println("Interrupted Exception!");
            } catch (Exception x) {
                System.out.println("Exception thrown.");
            }
        };

        Runnable runB = () -> demo.addElement("Hello!");

        try {
            Thread threadA1 = new Thread(runA, "A");
            threadA1.start();

            Thread.sleep(500);

            Thread threadA2 = new Thread(runA, "B");
            threadA2.start();

            Thread.sleep(500);

            Thread threadB = new Thread(runB, "C");
            threadB.start();

            Thread.sleep(1000);

            threadA1.interrupt();
            thread

A2.interrupt();
        } catch (InterruptedException x) {
            x.printStackTrace();
        }
    }
}

Output:

List is empty...
List is empty...
Opening...
New Element added:'Hello!'
notifyAll called!
Waiting...
Closing in AddElement method...
Hello!
Waiting...
List is empty...
Interrupted Exception!

9. String toString()

The toString() method returns a string representation of the object.

Example

class Person {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.setFirstName("Ramesh");
        person.setLastName("Fadatare");
        System.out.println(person.toString());
    }
}

Output:

Person [firstName=Ramesh, lastName=Fadatare]

Comments

  1. Nicely explained each Object class method with examples. keep posting such useful stuff.

    ReplyDelete
  2. “ Let's discuss one more example using the Closable interface and clone() method together.
    First, create a Person class which implements a Closable interface.”

    should be “Cloneable” not “Closable”

    ReplyDelete

Post a Comment

Leave Comment