A constructor is invoked to create an object using the new operator. Constructors are a special kind of method. They have three peculiarities:
- A constructor must have the same name as the class itself.
- Constructors do not have a return type—not even void.
- Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.
The constructor has exactly the same name as its defining class. Like regular methods, constructors can be overloaded (i.e., multiple constructors can have the same name but different signatures), making it easy to construct objects with different initial data values.
It is a common mistake to put the void keyword in front of a constructor. For example,
public void Circle() {
}
In this case, Circle() is a method, not a constructor.
Constructors are used to construct objects. To construct an object from a class, invoke a constructor of the class using the new operator, as follows:
new ClassName(arguments);
For example, new Circle() creates an object of the Circle class using the first constructor defined in the Circle class, and new Circle(25) creates an object using the second constructor defined in the Circle class.
A class normally provides a constructor without arguments (e.g., Circle()). Such a constructor is referred to as a no-arg or no-argument constructor.
A class may be defined without constructors. In this case, a public no-arg constructor with an empty body is implicitly defined in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly defined in the class.