How are this() and super() used with constructors?
this() constructor is invoked within a method of a class, if the execution of the constructor is to be done before the functionality of that method.
Example : void getValue()
{
this();
…
}
super() constructor is used within the constructor of the sub class, as the very first statement. This process is used when the super class constructor is to be invoked first, when the sub class object is instantiated everytime.
Example : class SubClass
{
SubClass()
{
super();
…..
}
How are this() and super() used with constructors?
super() needs to be the first statement in a constructor of a sub-class. However, if the sub-class needs to use this(), then even this() needs to be the first statement in a constructor.
In order to use both together, the following approach can be used: Class B extends A
{
Private int y1;
B(int x)
{
super();
}
B(int x, int y)
{
this(x);
y1 = y;
}
}