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.
Object() constructor The Object constructor turns the input into an object. Its behavior depends on the input's type. If the value is null or undefined , it will create and return an empty object. Otherwise, it will return an object of a Type that corresponds to the given value.
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors.
Constructors act like any other block of code (e.g., a method or an anonymous block). You can declare any variable you want there, but it's scope will be limited to the constructor itself.
A constructor is a special method of a class or structure in object-oriented programming that initializes a newly created object of that type. Whenever an object is created, the constructor is called automatically.
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!";
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With