The constructor has exactly the same name as the defining class. Like regular methods , constructors can be overloaded (i.e., multiple constructors with the same name but different signatures), making it easy to construct objects with different initial data values.
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(5) 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 called a no-arg or no-argument constructor .
A class may be declared without constructors. In this case, a no-arg constructor with an empty body is implicitly declared in the class. This constructor, called a default constructor , is provided automatically only if no constructors are explicitly declared in the class .
Note
Constructors are a special kind of method, with three differences:
|
Caution
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. |