2.2. Creating and Storing Objects: Constructors

A Java class defines what objects of the class know (attributes) and what they can do (behaviors). The class also defines how to initialize the attributes in instance variables when the object is first created using a special method called the constructor. Constructors are used to construct and initialize objects from the class, which is like a blueprint for the objects.

Constructors always have the same name as the class and are used with the keyword new. An object variable is created using the keyword new followed by a call to a constructor. For example, here’s how we used the World constructor to create a new graphical world, and the Turtle constructor to create a new Turtle.

// To create a new object, write:
// ClassName variableName = new ConstructorName(parameters);
World world = new World();
Turtle t = new Turtle(world);

There can be more than one constructor defined in a class. This is called overloading the constructor. There is usually constructor has no parameters (nothing inside the parentheses following the name of the constructor) like the World() constructor above. This simple constructor usually sets the attributes of the object to default values. There can be other constructors that have parameters like the Turtle(world) constructor call above. A parameter (also called actual parameter or argument) is a value that is passed into a constructor and used to initialize the attributes of an object.

The World class actually has 2 constructors. The default World() constructor creates a graphical screen of 640x480 pixels. The World(int w, int h) constructor takes two integer parameters, and initializes the World’s width and height to them, for example World(300,400) creates a 300x400 pixel world.

World world1 = new World(); // creates a 640x480 world
World world2 = new World(300,400); // creates a 300x400 world

The Turtle class also has multiple constructors, although it always requires a world as an parameter to know where to draw the turtle. The default location for the turtle is right in the middle of the world. Try the code below to see this.

There is another Turtle constructor that places the turtle at a certain (x,y) location in the world, for example at the coordinate (50, 100) below. The coordinate (0,0) is at the top left of the world.

Notice that the order of the parameters matter. This constructor always takes (x,y,world) as parameters in that order. Try mixing up the order of the parameters and you will see it causes an error because the parameters will not be the data types that it expects. This is one reason why programming languages have data types – for better error-checking.

Turtle t1 = new Turtle(world1);
Turtle t2 = new Turtle(50, 100, world1);

coding exercise Coding Exercise:

Try changing the code below to create a World of 300x400. What parameters do you need to give the Turtle constructor to place the turtle in the top right corner? Experiment and find out. What happens if you mix up the order of the parameters?

(If the code below does not work for you, you can also use the Turtle code at this repl.it link (refresh page after forking and if it gets stuck) or download the files here to use in your own IDE.)

You can also declare object variables without calling a constructor and set them equal to null which means that they have no value, for example Turtle t1 = null; but usually, you will want to call a constructor with new to create an object and store its memory address (a reference) in the variable.

2.2.1. Calendar Example

Here is another example. There is a class called GregorianCalendar in Java that can be used for dates and times. You can use this class by adding the line “import java.util.GregorianCalendar;” which will bring in this class library. Then, you can create an object variable called today that uses the default constructor to initialize it to the current date and time. Run the code below to see what it does. Note that the code below will return the current date and time on the server which might be different from the time where you are.

The GregorianCalendar class also has a constructor that takes a particular year, month (starting January at 0), and day as parameters to set up a specific date. Here’s the same program again but with a second variable that initializes the variable to the date 1/1/2020.

coding exercise Coding Exercise:

Run the code below to see the use of both constsructors. Try adding another GregorianCalendar object to the program for your birthdate and have it print it out. Which constructor do you need to use?

When you use a class that someone has already written for you in a library that you can import like the GregorianCalendar class above, you can look up how to use the constructors and methods in the documentation for that class. The documentation will list the signatures of the constructors or methods which will tell you their name and parameter list. The parameter list, in the header of a constructor, lists the formal parameters, declaring the variables that will be passed in as values and their data types. For example,

  • GregorianCalendar() : Constructs a default GregorianCalendar using the current time in the default time zone with the default locale.

  • GregorianCalendar(int year, int month, int dayOfMonth) : Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.

When a constructor like GregorianCalendar(2001,1,1) is called, the formal parameters, (year, month, dayOfMonth) in this example, are filled in with copies of the actual parameters (or arguments), which are (2001,1,1) in this example, using a process called call by value that copies values, and these values in turn are used by the constructor to initialize the instance variables for the new object.

Parameter Mapping

The type of the values being passed in as arguments have to match the type of the formal parameter variables. We cannot give a constructor a String when it is expecting an int. And the order of the arguments matters. If you mix up the year and month in the GregorianCalendar constructor, you will get a completely different date!

This lesson introduces a lot of vocabulary, but don’t worry if you don’t understand everything about classes and constructors yet. You will learn more how this all works in Unit 5 when you write your own classes and constructors.

2.2.2. groupwork Programming Challenge : Debugging

Debug the following code.

2.2.3. Summary

  • A class contains constructors that are invoked to create objects. Constructors must have the same name as the class.

  • Every object is created using the keyword new followed by a call to one of the class’s constructors.

  • Parameters allow values to be passed to the constructor to establish the initial state of the object. These values are called the parameters or actual parameters or arguments.

  • Constructors are said to be overloaded when there are multiple constructors with the same name but a different signature with different parameters. A signature consists of the constructor name and the parameter list.

  • The parameter list, in the header of a constructor, lists the types of the values that are passed and their variable names. These variables are called the formal parameters.

  • Actual parameters are passed using call by value which initializes the formal parameters with copies of the actual parameters. The values passed to a constructor must be compatible with the types identified in the formal parameter list.

You have attempted of activities on this page
Next Section - 2.3. Calling Methods Without Parameters