Constructor:
Constructor can be used to initialize member variable during object creation. Creating empty object can be avoided by writing parameterized constructor on own.
A default constructor will be created by compiler for every class we write in java that allow us to create empty object.
Example
class A { }
A default constructor A() {} will be added in the above class.
We can write our own parametrized constructor to change object creation behavior.
Example
class Employee { String name; int age; long ph; Employee(String n, int a) { name = n; age = a; } }
Now complier will not generate default constructs when we have our own Constructor.
Employee e1=new Employee(); // will create an error, Employee() cannot be found
The only way to create an object is by passing a String and int.
Employee e2=new Employee("mathan",33);