In Java a constructor is a special type of method, which is used to instantiate (create an object) the class.

A constructor must have the same name as the name of the class, it may be parameterised or without any parameter, constructors are solely used to instantiate a class and do not have return value.
public class Dog {

}
We can instantiate the above class as follows:
Dog dog = new Dog();
Here, Dog() is the constructor, that is called to create an object of 'Dog' class, this is called default constructor and we dont need to define it as Java provides it by default.

We can also define parameterised constructors and those constructors can be used to instantiate a class as shown below:
public class Dog {
	String name;
	String color;

	// parameterised constructor
	Dog(String name) {
		this.name = name;
	}

	// parameterised constructor
	Dog(String name, String color) {
		this.name = name;
		this.color = color;
	}
}
Now above class can be instantiated as follows:
Dog dog = new Dog("Bull Dog");
Dog dog = new Dog("Bull Dog","Brown");
The benefit of having parametersied constructors is to assign some values to the instance at the time of instantiation. (Details about 'this' keyword later.)

Note: Here this is worth noting that, as soon as we define any constructor, java stops providing the default constructor, this way Java helps us, if we do not want the class to be instantitated with default constructor.

If we still needs default constructor along with parameterised constructors we defined, we need to define the default constructor as well:
public class Dog {
	String name;

	// parameterised constructor
	Dog(String name) {
		this.name = name;
	}
	
	// default constructor
	Dog() {
	}
}

Difference between constructors and methods?

Constructors must have the same name as the class and can not have a return value. They are only called once for a single object while regular methods could be called many times and they may or may noy return a value.
  • By Techburps.com
  • Nov 7, 2017
  • Core Java