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?
source to share
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.
source to share