Constructor is a special method given in OOP language for creating and initializing object. In java, constructor role is only initializing object and new keyword role is creating object. In C++, constructor alone creates and initializes object.
Rules in defining constructor:
1) Constructor name should be same as class name.
2) It should not contain return type.
3) It should not contain modifiers.
4) In its logic, return statement with value is not allowed.
Note:
5) It can have all four accessibility modifiers(private,protected,default,public).
6) It can have parameters.
7) It can have throws clause-it means we can throw exception from constructor.
8) It can have logic, as part of logic it can have all legal statement except return statement with value.
9) We can place return; in constructor.
Constructor creation syntax is as follows
class Example { Example() { //All java legal statements are allowed except return statement ------; ------; ------; } }
Below application shows defining a class with constructor and its execution
class Example { Example() { System.out.println("constructor"); } public static void main(String[] args) { System.out.println("main"); Example e = new Example(); } }
Whenever we compile the java file by using javac Example.java '.class' file is generated and when we execute the '.class' file by using java Example '.class' file is loaded into JVM, then the first statement that is executed by JVM is the main method and later main is printed by using System.out.println statement. After that object creation statement is executed. In that statement whenever the control comes to new Example(), then object is created and constructor is initialized. One thing we should keep in mind that object is created first and then the constructor is initialized. Whenever the execution comes to new Example(), if you carefully observe in that statement Example() is a method. So thats why constructor is called and it is executed.So we can say that constructor is also a method but it has a different functionality like initializing object.