A constructor is a block of code that initializes an object immediately after the object is created. The structure of the constructor looks similar to a method.
declaring constructors
The general syntax for a constructor declaration is:
123 |
<Modifiers> <Constructor Name>(<parameters list>) throws <Exceptions list> { } |
The declaration of the constructor begins with a modifier.
The constructor can have its access modifier: public
, private
, protected
or package-level
(no modifier).
The constructor name is the same as the name of the class. The constructor name is followed by a pair of parentheses, which may include parameters. Optionally, the right parenthesis can be followed by a keyword followed by throws
a comma-delimited list of exceptions.
The following code shows an example of a constructor that declares a class Test
. The name of the class and the name of the constructor must match.
Click on the link to view the details
Java Constructors (constructors)