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.

Press + to interact
class Introduction
{
// A class can have its own variables
String name;
// This constructor requires the user to pass a String type variable or value
Introduction(String enteredName)
{
// We can read/update the value of a class's variable in the constructor
name = enteredName;
}
// This class has the following method
public void greet()
{
// We can read/update the value of a class's variable in the class's methods
System.out.format("Hello %s! This is AP CS A course.", name );
}
public static void main (String args[])
{
// Introduction class has only one constructor that takes String as input
Introduction user = new Introduction("Frodo Baggins");
// user is now an object, we can call all the methods on it e.g. greet() method
user.greet();
}
}

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 ...