What are the Object type objects that are useful for

I saw below code under practical questions in SCJP book

Object obj = new Object();

      

At first I thought it might be a bug since I didn't use such an operator. Now I understand that this is a valid statement.

I just want to understand what the practical use of this is, if any. What can you use for an object Object

(not a class derived from Object

) for?

+3


source to share


4 answers


The code declares a type reference Object

and assigns a dedicated instance to it Object

.

Now instances of the class Object

may seem pointless. However, they have practical applications. One of these methods is blocking:



...
synchronized (obj) {
   ...
}
...

      

+16


source


It can be used, for example, for synchronization:



synchronized (obj) {
   ... 
}

      

+1


source


Practical use is not that common (NPE's answer is one example), but since every class inherits from Object, when you call its constructor, the constructor of the Object class will be implicitly called at some time, so you'll need the ability to create a new object.

public class Foo {   // implicitly inherits from Object
    public Foo() {
        super(); // Object default constructor call
    }
}

public class Bar extends Foo {
    public Bar() {
        super(); // Foo default constructor call
    }
}

Bar b = new Bar();  // new Bar() calls new Foo() that calls new Object()

      

It is important to note that calls to super () (the superclass constructor) will be inserted implicitly by the compiler.

+1


source


With the new operator, you allocate memory for the object and call its constructor. Typically, the creation of an instance of the Object class is usually not displayed in everyday encoding. It's also important to know that every class you make extends from an object.

0


source







All Articles