CONSTRUCTOR

 
A constructor is a special method that is used to initialize a newly created object and is called just after the memory is allocated for the object.
It is not mandatory for the programmer to write a constructor for the class. If no user defined constructor is provided for a class, compiler initializes member variables to its default values.
Numeric data types are set to 0 .
Char data types are set to null character(\0)
Reference variables are set to null

In order to create a Constructor observe the following rules
1) It has the same name as the class
2) It should not return a value not even void

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class constructor<br>
    {
        constructor()
            {
                this(10);
                System.out.println("constructor()");
            }
        constructor (int i)
            {
                System.out.println("constructor (int)");
            }
        public static void main(String[] args)
            {
                constructor d1 = new constructor ();
                System.out.println("----------");
                constructor d2 = new constructor ();
                System.out.println("----------");
                constructor d3 = new constructor(20);
                System.out.println("----------");
            }
    }
O/P:

Constructors

NOTE:  
Constructor calling statement must be the first statement of the constructor.
We call a constructor while an object is created as per the parameters.
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class constructor2
    {
        constructor2  ()
            {
                System.out.println("constructor  ()");
            }
        constructor2  (int i)
            {
                this();
                System.out.println("constructor  (int)");
            }
        public  static void main(String[] args)

            {

                constructor2   e1 = new constructor2 ();
                System.out.println("---------");                      
                constructor2   e2 = new constructor2 (20);
                System.out.println("---------");
                constructor2  e3 = new constructor2 (10);
                System.out.println("---------");
            }
    }
O/P:

Constructors