Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the return type of a constructor in java?

As we know that we do not have to add any return type to a Java constructor.

class Sample{
  .....
  Sample(){
    ........
  }
}

In Objective C, if we create a constructor, it returns a pointer to its class. But it is not compulsory, I think.

AClass *anObject = [[AClass alloc] init];//init is the constructor with return type a pointer to AClass

Similarly, Is the constructor converted to a method which return a reference to its own class??

Like this:

class Sample{
    .....
    Sample Sample(){
      ........

      return this;
    }
}

Does the compiler add a return type a reference to same class to constructor? What is happening to a constructor? Any reference to study this?

EDIT:

Actually i want the answers to be at byte code level or JVM level or even below.

like image 664
sonu thomas Avatar asked Jan 15 '12 07:01

sonu thomas


2 Answers

Many have answered how constructors are defined in Java.

At the JVM level, static initialisers and constructors are methods which return void. Static initialisers are static methods, however constructors use this and don't need to return anything. This is because the caller is responsible for creating the object (not the constructor)

If you try to only create an object in byte code without calling a constructor you get a VerifyError. However on the oracle JVM you can use Unsafe.allocateInstance() to create an object without calling a constructor,

The static initialiser is called <cinit> which takes no arguments and the constructor is called <init>. Both have a void return type.

For the most part, this is hidden from the Java developer (unless they are generating byte code) however the only time you see these "methods" in stack traces (though you can't see a return type)

like image 132
Peter Lawrey Avatar answered Sep 20 '22 12:09

Peter Lawrey


While constructors are similar to methods, they are not methods. They have no return type, are not inherited, and cannot be hidden or overridden by subclasses.

Constructors are invoked by class instance-creation expressions (basically, the use of new), by explicit invocation from other constructors (using this(...) or super(...) syntax), and by the string concatenation operator. There is no other way to invoke a constructor (in particular, they cannot be invoked like other methods).

See Section 8.8 of the Java Language Specification for more info.

like image 41
Ted Hopp Avatar answered Sep 21 '22 12:09

Ted Hopp