Java Object class Tutorial

In this section, we will explain what is Java Object class and its work in Java programs.

What is Object class in Java?

The Object class is basically a Java pre-built class with a set of members.

By default, if we create a class and don’t extend it to any other classes, the compiler behind the scene will extend it to this `Object` class.

Even if we explicitly extend a class to another one and create a chain of classes that are inheriting from each other, at the top of this chain, there’s one class that does not extend explicitly to another class. So the compiler will implicitly extend that one to the `Object` class and so all other classes in the chain will have the access to the `Object` members as well.

List of Object class methods:

Here’s the list of methods in the `Object` class:

Note: in the description part, you’ll see we’re saying `this object` which means the current object that is calling the method.

Method

Description

clone()

Via this method, we can return a copy of the current object.

equal()

This method takes an object and compares it with the current object to see if they are equal or not. If they were equal, then the return value of the method will be true, otherwise it will be false.

finalize()

This method is used by the Garbage Collector on the object when it realizes that this object has no reference anymore.

getClass()

Via this method we will get the runtime class of this object.

hashCode()

Via this method, we can get the hash code of the object

notify()

This method is used in the concurrency to notify one single thread that is waiting on the object’s monitor.

notifyAll()

Via this method, we can wake up all the threads that are waiting on the object’s monitor.

toString()

Via this method, we can get the string representation of the object.

wait()

This method will cause the current thread to wait.

wait(long timeout)

This method will cause the current thread to wait for the amount of time that is declared as the argument of this method. (the value is in millisecond)

wait(long timeout, int nanos)

Just like the one before, but with more precision. (It takes millisecond as the first argument and nano second as the second argument)

Example: Object class in Java

public class Simple {
    public static void main(String[] args) {
        Simple simple = new Simple();
        System.out.println(simple.toString());
    }
}

Output:

tuto.Simple@48140564

The `Simple` class did not extend to any other classes so behind the scene compiler did extend this class to the `Object` class.

Now when we called the `toString()` method via this object, we’ve got the fully qualified named of the object + the hexadecimal representation of the object’s hash code.

In later sections we explained each of these methods in greater details.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies