How are this() and super() used with constructors? - Core Java

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;
   }
}
Purpose of finalization - Core Java
What is the purpose of finalization? - Finalization is the facility to invoke finalized() method. The purpose of finalization is to perform some action before the objects get cleaned up...
Difference between the File and RandomAccessFile classes - Core Java
Difference between the File and RandomAccessFile classes - The File class is used to perform the operations on files and directories of the file system of an operating system...
StringBuilder vs. StringBuffer - Core Java
Difference between StringBuilder and StringBuffer - StringBuffer is thread safe, where as StringBuilder is not. In other words, StringBuffer class is synchronized and StringBuilder class is not synchronized...
Post your comment