6

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.

10
  • 7
    I've seen it used to create an unambiguous locking object for threads, although there are far better ways to do concurrency. Jun 24, 2016 at 0:36
  • Ideally shouldn't you be using an AtomicReference<MyObject> foo; Jun 24, 2016 at 0:39
  • 1
    Why couldn't you explicitly extend Object? That's the implicit default. Jun 24, 2016 at 0:39
  • So is it completely valid code to say public class MyClass extends Object{} Jun 24, 2016 at 0:42
  • 1
    @amitmah: There are no separate "parent instances". Everything contributed by parent classes is folded into a single object instance.
    – Thilo
    Jun 24, 2016 at 2:03

1 Answer 1

8

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!";
    }
};
2
  • 3
    You can also extend Object in a named class (in fact, all classes implicitly do).
    – Thilo
    Jun 24, 2016 at 0:44
  • 1
    Thank you for a well laid out quality answer Jun 24, 2016 at 0:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.