What is constructor in java


                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.


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.


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);

Related Post