Skip to main content
Logo image

Section 1.13 Creating and Initializing Objects: Constructors

45 minutes
A Java class defines what objects of the class know (attributes) and what they can do (behaviors). Each class has constructors which are used to initialize the attributes in a newly created object. Constructors have the same name as the class.
A new object is created with the new keyword followed by the class name which is a call to the constructor (new ClassName()). For example, new World() creates and initializes a new object of the World class, and new Turtle(habitat) creates and initializes a new Turtle object in the World habitat. The new object is saved in a variable of a reference type which holds an object reference or null if there is no object.
// To create a new object and call a constructor write:
// ClassName variableName = new ClassName(arguments);
World habitat = new World();    // create a new World object
Turtle t = new Turtle(habitat); // create a new Turtle object

Subsection 1.13.1 The World Class Constructors

There can be more than one constructor defined in a class. This is called overloading the constructor. The World class has the 2 constructors seen below. One doesn’t take any arguments and creates a default sized world and one takes the world’s width and height arguments to create a world of a specific size. An argument is a value that is passed into a constructor. Arguments are used to initialize the attributes of an object, in this case, the size of the world.
Figure 1.13.1. Two World constructors
The no-argument constructor World(), with no arguments inside the parentheses following the name of the constructor, creates a graphical window with a default size of 640x480 pixels. No-argument constructors usually set the attributes of the object to default values. The second World(int width, int height) constructor takes two integer arguments, and initializes the World object’s width and height to them, for example new World(300,400) creates a 300x400 pixel world.
World world1 = new World(); // creates a default size 640x480 world
World world2 = new World(300,400); // creates a 300x400 world

Activity 1.13.1.

Which of these is valid syntax for creating and initializing a World object?
  • World w = null;
  • This declares a variable w that refers to a World object, but it doesn’t create a World object or initialize it.
  • World w = new World;
  • You must include parentheses () to call a constructor.
  • World w = new World();
  • Correct, use the new keyword followed by the classname and parentheses to create a new object and call the constructor.
  • World w = World();
  • You must use the new keyword to create a new object.
  • World w = new World(300,500);
  • Correct, this constructor call creates a new World object with the size 300x500 pixels.

Activity 1.13.2.

Which of these is overloading the constructor?
  • When a constructor takes one argument.
  • For a constructor to be overloaded there must be more than one constructor.
  • When a constructor takes more than one argument.
  • For a constructor to be overloaded there must be more than one constructor.
  • When one constructor is defined in a class.
  • For a constructor to be overloaded there must be more than one constructor.
  • When more than one constructor is defined in a class.
  • Overloading means that there is more than one constructor. The parameter lists must differ in either number, order, or type of parameters.

Subsection 1.13.2 The Turtle Class Constructors

The Turtle class also has multiple constructors, although it always requires a world as an argument in order to have a place to draw the turtle. The default location for the turtle is right in the middle of the world.
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.
Turtle t1 = new Turtle(world1);
Turtle t2 = new Turtle(50, 100, world1);

Note 1.13.2.

Notice that the order of the arguments matter. The Turtle constructor takes (x,y,world) as arguments in that order. If you mix up the order of the arguments it will cause an error, because the arguments will not be the data types that it expects. This is one reason why programming languages have data types – to allow for error-checking.

Activity 1.13.3.

Which of these is valid syntax for creating and initializing a Turtle object in world1?
  • Turtle t = Turtle(world1);
  • You must use the new keyword to create a new Turtle.
  • Turtle t = new Turtle();
  • All turtle constructors take a world as an argument.
  • Turtle t = new Turtle(world1, 100, 100);
  • The order of the parameters matter, so this would cause a syntax error.
  • Turtle t = new Turtle(100, 100, world1);
  • This creates a new Turtle object in the passed world at location (100,100)

Activity 1.13.4.

Try changing the code below to create a World object with 300x400 pixels. Where is the turtle placed by default? What arguments do you need to pass to the Turtle constructor to put the turtle at the top right corner? Experiment and find out. What happens if you mix up the order of the arguments?

Subsection 1.13.3 Object Variables and References

New objects are saved in variables of a reference type which holds a reference to an object. A reference is a way to find the object in memory. It is like a tracking number that you can use to track the location of a package in the mail.
A special reference value null (which means none) can be used when a variable doesn’t refer to any object. For instance, you can declare a variable and initialize it to null (Turtle t1 = null;) meaning the variable doesn’t refer to any object yet.
Watch the video
 1 
https://www.youtube.com/watch?v=5fpjgXAV2BU&list=PLHqz- wcqDQIEP6p1_0wOb9l9aQ0qFijrP&ab_channel=colleenlewis
below about null.
The code Turtle t1 = null; creates a variable t1 that refers to a Turtle object, but the null means that it doesn’t refer to an object yet. You could later create the object and set the object variable to refer to that new object (t1 = new Turtle(world1)). Or more commonly, you can declare an object variable and initialize it in the same line of code (Turtle t2 = new Turtle(world1);).
World world1 = new World();
Turtle t1 = null;
t1 = new Turtle(world1);
// declare and initialize t2
Turtle t2 = new Turtle(world1);

Subsection 1.13.4 Constructor Signatures

When you use a class that someone has already written for you in a library that you can import like the Turtle class above, you can look up how to use the constructors and methods in the documentation
 2 
https://www2.cs.uic.edu/~i101/doc/Turtle.html
for that class. The documentation will list the signatures (or headers) of the constructors or methods which will tell you their name and parameter list. The parameter list, in the header of a constructor, is an ordered list of variable declarations which includes data types. The parameter variables will store the argument values passed into the constructor.
Constructors are said to be overloaded when there are multiple constructors, but the constructors have different signatures. They can differ in the number, type, and/or order of parameters. For example, here are the two constructors for the Turtle class that take different parameters:
Figure 1.13.3. Turtle Class Constructor Signatures and Parameters

Activity 1.13.5.

Given the Turtle class in the figure above and a World object world1, which of the following code segments will correctly create an instance of a Turtle object at (x,y) coordinates (50,150)?
  • Turtle t = new Turtle();
  • There is no Turtle constructor that takes no arguments according to the figure above.
  • Turtle t = new Turtle(50,150);
  • There is no Turtle constructor that takes 2 arguments according to the figure above.
  • Turtle t = new Turtle(world1);
  • This would initialize the Turtle to the middle of the world, not necessarily coordinates (50,150).
  • Turtle t = new Turtle(world1,50,150);
  • Make sure the order of the arguments match the constructor signature above.
  • Turtle t = new Turtle(50,150,world1);
  • This matches the second constructor above with the parameters of x, y, and world.
In Unit 3, you will learn to write your own classes. However, if you see a class definition on the AP exam, like the one below for a class called Date, you should be able to pick out the attributes (instance variables) and the constructors and know how to use them.
Figure 1.13.4. A Date class showing attributes and constructors

Activity 1.13.6.

Activity 1.13.7.

Given the Date class in the figure above and assuming that months in the Date class are numbered starting at 1, which of the following code segments will create a Date object for the date September 20, 2020 using the correct constructor?
  • Date d = new Date();
  • This would initialize the date attributes to today’s date according to the constructor comment above, which might not be Sept. 20, 2020.
  • Date d = new Date(9,20);
  • There is no Date constructor that takes 2 arguments according to the figure above.
  • Date d = new Date(9,20,2020);
  • The comment for the second constructor in the Date class above says that the first argument must be the year.
  • Date d = new Date(2020,9,20);
  • This matches the second constructor above with the parameters year, month, day.
  • Date d = new Date(2020,20,9);
  • Make sure the order of the arguments match the constructor signature above.

Subsection 1.13.5 Arguments, Parameters, and Call by Value

When a constructor like Date(2005,9,1) is called, the parameters, (year, month, and day), are set to copies of the arguments, (2005, 9, and 1). This is call by value which means that copies of the argument values are passed to the constructor. These values are used to initialize the object’s attributes. A constructor call interrupts the sequential execution of statements in that the program executes the statements in the constructor before continuing. Once the last statement in the constructor has been executed, the flow of control is returned to the point immediately following where the constructor was called.
Figure 1.13.5. Parameter Mapping
The type of the values being passed in as arguments have to match the type of the parameter variables. We cannot give a constructor a String object when it is expecting an int. The order of the arguments also matters. If you mix up the month and the day in the Date constructor, you will get a completely different date, for example January 9th (1/9) instead of Sept. 1st (9/1).

Activity 1.13.8.

In public World(int width, int height) what are width and height?
  • objects
  • Objects have attributes and behavior.
  • classes
  • A class defines the data and behavior for all objects of that type.
  • parameters
  • The parameters are in the constructor’s signature.
  • arguments
  • An argument is the value that is passed into the constructor.

Activity 1.13.9.

In new World(150, 200) what are 150 and 200?
  • objects
  • Objects have attributes and behavior.
  • classes
  • A class defines the data and behavior for all objects of that type.
  • parameters
  • A parameter is in the constructor’s signature.
  • arguments
  • An argument is the value that is passed into the constructor.

Activity 1.13.10.

Debug the following code.
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 about how this all works in later units when you write your own classes and constructors. And you will see parameters again with methods in the next lessons.

Subsection 1.13.6 Coding Challenge: Custom Turtles

Working in pairs, you will now look at a new class called CustomTurtle and design some colorful turtles with its constructors. The CustomTurtle class in the ActiveCode below inherits many of its attributes and methods from the Turtle class. However, it has some new constructors with more parameters to customize a turtle with its body color, shell color, width, and height. CustomTurtle has 3 constructors:
/** Constructs a CustomTurtle in the middle of the world */
public CustomTurtle(World w)

/** Constructs a CustomTurtle with a specific body color,
    shell color, and width and height in the middle of the world */
public CustomTurtle(World w, Color body, Color shell, int w, int h)

/** Constructs a CustomTurtle with a specific body color,
    shell color, and width and height at position (x,y) in the world */
public CustomTurtle(int x, int y, World w, Color body, Color shell, int w, int h)
You will use the constructor(s) to create the CustomTurtles below. You can specify colors like Color.red by using the Color
 3 
docs.oracle.com/en/java/javase/22/docs/api/java.desktop/java/awt/Color.html
class in Java.
  1. Create a large 150x200 (width 150 and height 200) CustomTurtle with a green body (Color.green) and a blue shell (Color.blue) at position (150,300)
  2. Create a small 25x50 CustomTurtle with a red body and a yellow shell at position (350,200)
  3. Create a CustomTurtle of your own design.

Project 1.13.11.

Use the CustomTurtle constructors with the signatures below to create the turtles with the colors and positions described in the comments of the program.
/** Constructs a
         CustomTurtle in the middle of the world */ public CustomTurtle(World
         w) /** Constructs a CustomTurtle with a specific body color, shell
         color, and width and height in the middle of the world */ public
         CustomTurtle(World w, Color body, Color shell, int w, int h) /**
         Constructs a CustomTurtle with a specific body color, shell color, and
         width and height at position (x,y) in the world */ public
         CustomTurtle(int x, int y, World w, Color body, Color shell, int w,
         int h)

Subsection 1.13.7 Summary

  • (AP 1.13.A.1) A class contains constructors that are called with the keyword new to create objects and initialize its attributes.
  • (AP 1.13.A.1) Constructors have the same name as the class.
  • (AP 1.13.C.1) An object is typically created using the keyword new followed by a call to one of the class’s constructors. new ClassName() creates a new object of the specified class and calls a constructor.
  • (AP 1.13.B.1) The new object is saved in a variable of a reference type which holds an object reference or null if there is no object.
  • (AP 1.13.A.2) A constructor signature consists of the constructor’s name, which is the same as the class name, and the ordered list of parameter types.
  • (AP 1.13.A.2) The parameter list, in the header of a constructor, lists the types of the values that are passed and their variable names.
  • (AP 1.13.A.3) Constructors are said to be overloaded when there are multiple constructors with different signatures. They must differ in the number, type, or order of parameters.
  • A no-argument constructor is a constructor that doesn’t take any passed in values (arguments).
  • (AP 1.13.C.2) Parameters allow constructors to accept values to establish the initial values of the attributes of the object.
  • (AP 1.13.C.3) A constructor argument is a value that is passed into a constructor when the constructor is called. The arguments passed to a constructor must be compatible in order and number with the types identified in the parameter list in the constructor signature.
  • (AP 1.13.C.3) When calling constructors, arguments are passed using call by value. Call by value initializes the parameters with copies of the arguments.
  • (AP 1.13.C.4) A constructor call interrupts the sequential execution of statements, causing the program to first execute the statements in the constructor before continuing. Once the last statement in the constructor has been executed, the flow of control is returned to the point immediately following where the constructor was called.

Subsection 1.13.8 AP Practice

Activity 1.13.12.

Consider the following class. Which of the following successfully creates a new Cat object?
public class Cat
{
    private String color;
    private String breed;
    private boolean isHungry;

    public Cat()
    {
        color = "unknown";
        breed = "unknown";
        isHungry = false;
    }

    public Cat(String c, String b, boolean h)
    {
        color = c;
        breed = b;
        isHungry = h;
    }
}

I.   Cat a = new Cat();
II.  Cat b = new Cat("Shorthair", true);
III. String color = "orange";
     boolean hungry = false;
     Cat c = new Cat(color, "Tabby", hungry);
  • I only
  • I is one of the correct constructors but the second constructor can also be used.
  • I and II
  • II is not correct because there is no Cat constructor with 2 parameters.
  • I and III
  • I and III call the correct constructors.
  • I, II, and III
  • II is not correct because there is no Cat constructor with 2 parameters.
  • II and III
  • II is not correct because there is no Cat constructor with 2 parameters.

Activity 1.13.13.

Consider the following class. Which of the following code segments will construct a Movie object m with a title of β€œLion King” and rating of 8.0?
public class Movie
{
    private String title;
    private String director;
    private double rating;
    private boolean inTheaters;

    public Movie(String t, String d, double r)
    {
        title = t;
        director = d;
        rating = r;
        inTheaters = false;
    }

    public Movie(String t)
    {
        title = t;
        director = "unknown";
        rating = 0.0;
        inTheaters = false;
    }
}
  • Movie m = new Movie(8.0, "Lion King");
  • There is no Movie constructor with 2 parameters.
  • Movie m = Movie("Lion King", 8.0);
  • There is no Movie constructor with 2 parameters.
  • Movie m = new Movie();
  • This creates a Movie object but it does not have the correct title and rating.
  • Movie m = new Movie("Lion King", "Disney", 8.0);
  • This creates a Movie object with the correct title and rating.
  • Movie m = new Movie("Lion King");
  • This creates a Movie object but it does not have a rating of 8.0.
You have attempted of activities on this page.