Rohan Jhunjhunwala Rohan Jhunjhunwala - 5 months ago 11
Java Question

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.

Answer

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!";
    }
};
Comments