12/14/2008

super() and this()

Basically, super() is automatically generated in a constructor.

super() calls the constructor of its superclass.
this() calls no-argument constructor in its class.
The constructor of the Object class is always called at last, because the Object class is the super class of every class.
You can add an argument(s) in super() and this() 
You cannot use super() and this() in the same block.
Either super() or this() must be written first in a constructor.

Sample sample = new Sample(1) 
In the example below, super() is automatically generated in the constructor that has an argument.
class Sample {
    Sample() { }
    Sample(int a) { }     // super() is automatically generated
}

In the example below, super() is automatically generated in the no-argument constructor.
class Sample {
    Sample() { }     // super() is automatically generated
    Sample(int a) {this();}
}