A constructor is a special method used to initialize objects in java.
We use constructors to initialize all variables in the class when an object is created. As and when an object is created it is initialized automatically with the help of constructor in java.
We have three types of constructors
- Default Constructor
- No-arg constructor
- Parameterized Constructor
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Example2 { private int var; //default constructor public Example2() { this.var = 10; } //parameterized constructor public Example2(int num) { this.var = num; } public int getValue() { return var; } public static void main(String args[]) { Example2 obj = new Example2(); Example2 obj2 = new Example2(100); System.out.println("var is: " + obj.getValue()); System.out.println("var is: " + obj2.getValue()); } } |
Output:-
1 2 |
var is: 10 var is: 100 |