Why do constructors in java not have a return type? [duplicate]
Possible Duplicate:
Why constructor not returns value
Why don't constructors have a return type, not even void? What's the reason for that?
Constructor is internally a nonstatic method with name <init>
and void
return type. It does not return anything. Internally first object is allocated and then its constructor is called. Object is not allocated with constructor itself.
In other words the syntax new Object()
not only calls the constructor but also creates new object and after calling the constructor returns it. The Suns' Java tutorial stands that "The new operator is followed by a call to a constructor, which initializes the new object." Initialize does not mean create.
Answering the question. Missing return type declaration is a way in which you distinguish the constructor from a method. But you can return from constructor as from void method. For example this code compiles and runs correctly:
public class TheClass {
public TheClass(){
return;
}
public void TheClass(){ //confusing, but this is void method not constructor
return;
}
public static void main(String[]a){
TheClass n = new TheClass();
n.TheClass();//void method invocation
}
}
This class has one void method (don't try it at home - uppercase method is a bad style) and one constructor. The difference is in declared return type.
Look at this JNI code snippet which demonstrates that constructor is a nonstatic void method:
jstring
MyNewString(JNIEnv *env, jchar *chars, jint len)
{
jclass stringClass;
jmethodID cid;
jcharArray elemArr;
jstring result;
stringClass = (*env)->FindClass(env, "java/lang/String");
if (stringClass == NULL) {
return NULL; /* exception thrown */
}
/* Get the method ID for the String(char[]) constructor */
cid = (*env)->GetMethodID(env, stringClass,
"<init>", "([C)V");
if (cid == NULL) {
return NULL; /* exception thrown */
}
/* Create a char[] that holds the string characters */
elemArr = (*env)->NewCharArray(env, len);
if (elemArr == NULL) {
return NULL; /* exception thrown */
}
(*env)->SetCharArrayRegion(env, elemArr, 0, len, chars);
result = (*env)->AllocObject(env, stringClass);
if (result) {
(*env)->CallNonvirtualVoidMethod(env, result, stringClass,
cid, elemArr);
/* we need to check for possible exceptions */
if ((*env)->ExceptionCheck(env)) {
(*env)->DeleteLocalRef(env, result);
result = NULL;
}
}
/* Free local references */
(*env)->DeleteLocalRef(env, elemArr);
(*env)->DeleteLocalRef(env, stringClass);
return result;
}
especially these fragments:
/* Get the method ID for the String(char[]) constructor */
cid = (*env)->GetMethodID(env, stringClass, "<init>", "([C)V");
and then
/* Allocate new object. */
result = (*env)->AllocObject(env, stringClass);
if (result) {
/* Call uninitialized objects' constuctor. */
(*env)->CallNonvirtualVoidMethod(env, result, stringClass, cid, elemArr);
first object is allocated and then nonstatic <init>
method is called. For details look here. The AllocObject function documentation stands that "Allocates a new Java object without invoking any of the constructors for the object. Returns a reference to the object." So in JVM object is not allocated by constructor, but only initialized by it. Looking in constructors' bytecode we are seeing that no object is returned (exactly like in void methods).
Another way, when you dissasemble sample class, you will see invocation of parent (Object) constructor from its constructor:
#javap -c NewClass
Compiled from "NewClass.java"
public class NewClass extends java.lang.Object{
public NewClass();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
}
Note that the <init>
method is not actually part of the Java language. Rather, it is something the Java virtual machine expects to see in a Java class file. This distinction is significant because the Java language does not depend on the class file. Java source can be compiled into other binary formats, including native executables. A Java compiler that translates Java language source into some other binary format need not generate a method named <init>
, so long as objects are initialized in the proper way at the proper time. The Java Language Specification (JLS) details the order of initialization and when it occurs, but doesn't say how it is actually accomplished.
But I see that we're talking about JVM here.
For some of nonbelievers this is example (thx biziclop) which shows that object exists and is allocated before returning from constructor:
class AnotherClass {
private String field;
public static AnotherClass ref;
public AnotherClass() {
this.field = "value";
AnotherClass.ref = this;
throw new RuntimeException();
}
@Override
public String toString() {
return field;
}
}
public class MainClass {
public static void main(String[] a) {
try {
new AnotherClass();
return;
} catch (RuntimeException ex) {
System.out.println("exception");
}
System.out.println("instance: " + AnotherClass.ref);
}
}
How would you get the returned value? What kind of value are you interested in, being returned? How would you declare the return type?
X x = new X ();
assigns an X-reference to x. Now, if new X
would return something, how should you get it?
class X {
public int X () {
return 42;
}
}
What's the logic of returning something from the ctor? An error message? Some loginfo? Write it to a file, or to an attribute, which you poll later.
Since the ctor is only accessed once per object, the only reason I can think of, to use another return value, would be, to inform about the process of creation itself.
class X {
private Y y;
public int X () {
y = new Y ();
}
public Y getY () { return y; }
}
Even though the VM implementation of a constructor isn't to return any value, in practice it kind of does - the new object's reference. It would then be syntactically weird and / or confusing to be able to store one or both of the new object's reference and an additional return value in one statement.