Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a Java constructor return the Object reference?

I know Java's constructors can't have any type and interestingly it cannot even be void. A logical explanation for that would be that a constructor returns the initialized object's reference.

MyClass myObject = new MyClass();

The constructor of myClass will now return the object reference after instantiating it and save it in the object variable MyObject and that's why the constructor can't have a return type.

Is that right? Could someone confirm this?

like image 918
philx_x Avatar asked Oct 29 '14 08:10

philx_x


1 Answers

No, actually, the constructors are compiled into the class file like methods having the name <init> and a void return type. You can see these "<init>" invocations in stack traces. The expression new Type() is compiled as an instruction new which just creates the instance of Type and an additional method invokation (invokespecial) to one of the constructors declared in Type.

The verifier will ensure that such a special method is invoked at exactly once on a newly created instance and that it is called before any other use of the object.

It’s just a programming language design decision to let constructors have no return type from the Java language point of view. After all, new Type(…) is an expression that evaluates to the newly created instance of Type and you can’t get a return value from the constructor with that programming language construct. Further, if you add a return type, Java will unconditionally assume that it is a method, even if it has the same name as the class.

That’s simply how it was defined: (It makes parsing the class definition easier)

The SimpleTypeName in the ConstructorDeclarator must be the simple name of the class that contains the constructor declaration, or a compile-time error occurs.

In all other respects, a constructor declaration looks just like a method declaration that has no result (§8.4.5).

like image 80
Holger Avatar answered Nov 14 '22 22:11

Holger