Rohan Jhunjhunwala
Rohan Jhunjhunwala

Reputation: 416

Is there legitimate use for object constructor?

What would the legitimate use of the following code be?

Object o =new Object();

From what I understand this object has no use and carries no real data (except for maybe its hash code). Why would this be used? Is it acceptable practice. If I am able to do this could I explicitly extend the object class.

Upvotes: 6

Views: 129

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

From what I understand this object has no use and carries no real data (except for maybe its hash code)

The object carries its identity and its monitor. That is why this assignment is used to create object monitors that are separate from the object itself.

Why would this be used? Is it acceptable practice?

The only use that I've seen for this making an object to be used as a monitor for other objects.

If I am able to do this could I explicitly extend the object class?

Absolutely. You can extend an object in an anonymous class, like this:

Object obj = new Object() {
    @Override
    public String toString() {
        return "Hello, world!";
    }
};

Upvotes: 8

Related Questions