Page 120 - 2617_JSSPS_C-7
P. 120
DIFFERENT TYPES OF CONSTRUCTORS
In Java, there are four different types of constructors which are default, non-parameterised,
parameterised and copy constructors.
Default Constructor
If a constructor is not defined in a class, then the Java compiler provides a constructor which is known
as default constructor. It does not have any parameter and statements in its body. For example:
class demo
{
public demo() //default constructor
{
}
}
A default constructor is used to initialize the instance variables automatically with default values. For
example, int is initialized by 0, double is initialized by 0. String is initialized by null. Let us take an
example given below:
1 class default_cons
2 {
3 int a;
4 double b;
5 String s;
6 void print()
7 {
8 System.out.println("Integer : " + a);
9 System.out.println("Double : "+ b);
10 System.out.println("String : "+ s);
11 }
12 public static void main(String[] args)
13 {
14 default_cons ob = new default_cons();
15 ob.print();
16 }
17 }
Parameterised Constructor
A parameterised constructor is a type of constructor with parameters and statements inside its body.
Number of parameters may be different depending on the number of instance variables.
Premium Edition-VII
118

