Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there legitimate use for object constructor?

Tags:

java

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.

like image 212
Rohan Jhunjhunwala Avatar asked Jun 24 '16 00:06

Rohan Jhunjhunwala


People also ask

What is the purpose of object constructor?

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.

Do you need a constructor for an object?

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.

Can we define object for constructor?

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.

Why do we use constructor in OOP?

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.


Video Answer


1 Answers

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!";
    }
};
like image 65
Sergey Kalinichenko Avatar answered Oct 21 '22 05:10

Sergey Kalinichenko