π5.2: Constructors
Table of Contents
π This page is a condensed version of CSAwesome Topic 5.2
Writing Constructors
In Unit 2, we learned how to create objects by calling constructors.
π£ To review, a call to a constructor consists of the word new
followed by the name of the class
being constructed, and then an argument list in parentheses:
// To create a new object, write:
// ClassName variableName = new ConstructorName(arguments);
World world = new World();
Turtle t = new Turtle(world);
Person p = new Person("Pat", "pat@gmail.com", "123-456-7890");
This is how we create specific
World
,Turtle
, andPerson
objects as instances of their classes.
Now itβs time to learn to write our own constructors.
Constructor Signature
In the source code for a class, constructors are usually written after the instance variables and before any methods.
β°ποΈ The signature of a constructor is similar to the signature of a method except there is no return type, not even void
, and instead of a method name, the name of the constructor is the same as the name of the class.
Other details: The constructors you write will almost always be marked
public
. Like methods, constructors also have a parameter list specified in parenthesis that declare the variables that will be used to hold the arguments passed when the constructor is called.
public class ClassName
{
/* Instance variable declarations go here, before constructors */
/* Constructor - same name as Class, no return type */
public ClassName()
{
/* Implementation not shown */
}
/* Method definitions go here, after constructors */
}
β οΈ Constructors must have the same name as the class
! Constructors have no return type!
The Job of a Constructor
The job of a constructor is to set the initial values for the objectβs instance variables to βusefulβ values. But what does βusefulβ mean?
Sometimes we describe the values of all an objectβs instance variables at a given time as the objectβs state. And we say an object is in a valid state when all its instance variables have values that let us use the object by invoking its public methods.
ποΈπ§± So another way to describe the job of a constructor is to set up a specific objectβs instance values so itβs in a valid state β essentially, using the blueprint (class) to crate a usable object with data.
Classes can have zero or more constructors but they should all produce an object in a valid, usable state.
Default no-argument constructor
The easiest way to write a constructor is to not write one. If you do not write a constructor, your class will automatically get what is called the default no-argument constructor. This constructor will initialize all your instance variables to the default value for their data type:
- 0 for
int
anddouble
false
forboolean
null
for all reference (object) types likeString
.
In the (rare) case where those default values are sufficient to put your object into a valid state, you may not need to write a constructor at all.
Constructors that take arguments
Usually, however, if you are writing a class that has instance variables, you need to initialize your instance values to some specific values. In that case you probably need to write a constructor that takes arguments and uses them to initialize your instance variables.
Consider the constructor from the Person
class from the last section. This constructor ensures that all three of the instance variables (name
, email
, and phoneNumber
) in Person
are initialized to the values provided by whatever code called the constructor:
public Person(String initName, String initEmail, String initPhone)
{
name = initName;
email = initEmail;
phoneNumber = initPhone;
}
For example, in the constructor call
new Person("Pat", "pat@gmail.com", "123-456-7890")
, the argument βPatβ is passed into the parameter variableinitName
, which the constructor then assigns to the instance variablename
.
One important note: if you DO write a constructor, Java will NOT generate the default constructor automatically for you. This is a good thing because it lets you make sure that instances of your class are always properly initialized.
With this constructor in place, for instance, thereβs no way to construct a
Person
object without providing the three requiredString
values.
Overloading constructors
Sometimes you will want to write more than one constructor so there are different ways of making an instance of your class.
Writing multiple methods that the same NAME but accept different ARGUMENTS is called overloading. One reason to overload constructors is to make it convenient to create instances from different kinds/combinations of arguments.
We discussed overloading in Chapter 2 from the perspective of calling methods with the same name, but providing different amounts of information: like
String.substring(int from)
andString.substring(int from, int to)
.
For instance, suppose we were writing a program that had another class AddressBookEntry
which had getters for name, email, and phone number. In that program it might be useful to write another Person
constructor like this:
public Person(AddressBookEntry address) {
{
name = address.getName();
email = address.getEmail();
phoneNumber = address.getPhoneNumber();
}
Most of the time, you might still even want to provide a no-argument constructor. If thereβs a valid object that you can create without any arguments, you could write a no-argument constructor for Person
like:
public Person()
{
name = "Anonymous";
email = "unknown";
phoneNumber = "unknown";
}
Itβs up to you to decide if this is actually a useful value to have or if it would be better to force the users of the
Person
class to choose the values themselves.
π» In-Class Activity: Student Class
βοΈ Summary
-
Constructors are used to set the initial state of an object, which includes initial values for all instance variables.
-
When no constructor is written, Java provides a no-argument default constructor, and the instance variables are set to their default values (0 for
int
anddouble
,null
for objects likeString
). -
Constructor parameters are local variables to the constructor and provide data to initialize instance variables.
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.