Friday, 20 July 2018

SE - 24 - Default constructor in Java

Default constructor is automatically generated in JAVA when there are no constructors present or defined by user. Few important things about default constructor :

i) It is only created automatically by java if there are no defined constructors in the class

ii) It has no arguments or body

iii) It initialises the member data value with the default values. It initializes only the uninitilized variables. : Eg :

class DefaultConstTest {
   int i;
   DefaultConstTest t;
   boolean b;
   byte bt;
   float ft;
}
Since there are no constructors here so java will automatically run the default constructor and assign default value to its members :

Here the Value assigned will  be:

0
null
false
0
0.0

iv) If we say how the default constructor looks like , then simply it's a constructor with no arguments and body. It will look like :

DefaultConstTest() {}

v) If we create our own constructor then java will not create any default constructor

vi) The no-arg constructor and default constructor are not same. The no-arg constructor is defined by user while default constructor is created by JAVA

No comments:

Post a Comment