Constructors
Take a deeper look at class constructors in this lesson.
Constructors are a special type of methods that are used to instantiate objects of a class. As we saw in the last couple of lessons, a class gives the blueprint of a non-primitive data type. To create objects from this class, we need constructors.
The code for a simple Introduction class is reproduced below. Let’s take a look at the anatomy of the constructor below.
Signature
The constructor’s signature defines what types of parameters it requires as input. For example, in our case, we only need a String type variable: enteredName. However, a constructor can have any number and type of parameters.
-
We can have a constructor with no parameters. In this case, we will leave the parenthesis empty.
class Introduction() -
We can also have any number of parameters. For example, the following signature takes three
Stringtype parameters.class Introduction(String enteredName, String secondName, String