Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a constructor only return an object?

If there is a constructor like

function a() {}

then

(new a) instanceof a === true

But on the other hand,

function a() { return {} }

results in

(new a) instanceof a === false

So what I was thinking is that

function a() { return 123 }

would result in the same thing. However, when returning a Number,

(new a) instanceof a === true

How is this possible? Why can't I make a constructor return something else than an Object?

(I do know making a constructor returning a Number is rather useless but I would like to understand the 'why' of this behaviour)

like image 975
pimvdb Avatar asked Jul 21 '11 11:07

pimvdb


People also ask

Why can't constructors have a return type?

Since constructor can only return the object to class, it's implicitly done by java runtime and we are not supposed to add a return type to it. If we add a return type to a constructor, then it will become a method of the class. This is the way java runtime distinguish between a normal method and a constructor.

Does a constructor return an object?

No, constructor does not return any value. While declaring a constructor you will not have anything like return type. In general, Constructor is implicitly called at the time of instantiation. And it is not a method, its sole purpose is to initialize the instance variables.

Why do constructors not return values in Java?

So the reason the constructor doesn't return a value is because it's not called directly by your code, it's called by the memory allocation and object initialization code in the runtime. Its return value (if it actually has one when compiled down to machine code) is opaque to the user - therefore, you can't specify it.

Can a constructor ever have a return type?

No, constructor does not have any return type in Java. Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. Mostly it is used to instantiate the instance variables of a class.


1 Answers

According to the spec: If calling the constructor returns an object, then this object is the result of the new-expression. If the constructor doesn't return an object (but undefined or some other primitive value), the result is the newly created object.

If primitives were allowed, then all constructors would have to explicitly return something (typically "this"), otherwise the result would be undefined (because the result of a function without a return is undefined). That would be a needless hassle.

Additionally, it makes sense that new can be relied on to always return an object.

like image 73
JacquesB Avatar answered Sep 29 '22 01:09

JacquesB