2.2. Creating and Initializing Objects: Constructors

A Java class defines what objects of the class know (attributes) and what they can do (behaviors). Each class has constructors like World() and Turtle(world) which are used initialize the attributes in a newly created object.

A new object is created with the new keyword followed by the class name (new Class()). When this code executes, it creates a new object of the specified class and calls a constructor, which has the same name as the class. For example, new World() creates and initializes a new object of the World class, and new Turtle(world) creates and initializes a new Turtle object in the specified world.

// To create a new object and call a constructor write:
// ClassName variableName = new ClassName(parameters);
World world = new World();    // create a new World object
Turtle t = new Turtle(world); // create a new Turtle object

2.2.1. Overloading Constructors, the No-Argument Constructor, and Parameters

There can be more than one constructor defined in a class. This is called overloading the constructor. There is usually a constructor that has no parameters (nothing inside the parentheses following the name of the constructor) like the World() constructor above. This is also called the no-argument constructor. The no-argument constructor usually sets the attributes of the object to default values. There can also be other constructors that take 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. It can be used to initialize the attribute of an object. The World class actually has 2 constructors. One doesn’t take any parameters and one takes the world’s width and height.

Two overloaded World constructors

Figure 1: Two overloaded World constructors

exercise Check your understanding

    2-2-1: Which of these is overloading?

  • When a constructor takes one parameter.
  • For a constructor to be overloaded there must be more than one constructor.
  • When a constructor takes more than one parameter.
  • 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.

    2-2-2: 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();
  • 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.

2.2.2. The World Class Constructors

The constructor that doesn’t take any parameters, World(), creates a graphical window with 640x480 pixels. The World(int width, int height) constructor takes two integer parameters, 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 640x480 world
World world2 = new World(300,400); // creates a 300x400 world

Note

The turtle word does not use the cartesian coordinate system. The top left corner is (0,0), x increases to the right, and y increases towards the bottom of the page.

../_images/coords.png

Figure 2: The coordinate (0,0) is at the top left of the Turtle world.

2.2.3. The Turtle Class Constructors

The Turtle class also has multiple constructors, although it always requires a world as an parameter 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

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

exercise Check your understanding

    2-2-3: Which of these is valid syntax for creating and initializing a Turtle object?

  • Turtle t = Turtle(world);
  • You must use the new keyword to create a new Turtle.
  • Turtle t = new Turtle();
  • All turtle constructors take a world as a parameter.
  • Turtle t = new Turtle(world, 100, 100);
  • The order of the parameters matter.
  • Turtle t = new Turtle(100, 100, world);
  • This creates a new Turtle object in the passed world at location (100,100)

coding exercise Coding Exercise:

Try changing the code below to create a World object with 300x400 pixels. Where is the turtle placed by default? What parameters 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 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.)

2.2.4. Object Variables and References

You can also declare an object variable and initialize it to null (Turtle t1 = null;). An object variable holds a reference to an object. A reference is a way to find the object in memory. A reference is like a tracking number that you can use to track the location of a package. 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(world)). However, you will typically declare an object variable and initialize it in the same line of code (Turtle t2 = new Turtle(world);).

World world = new World();
Turtle t1 = null;
t1 = new Turtle(world);
Turtle t2 = new Turtle(world);

Note

Notice that you only specify the type (class name) for an object reference when you declare it (Turtle t1 = null) and not when you assign it a value (t1 = new Turtle(world)).

2.2.5. Constructor and Method 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 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. Constructors are 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 two constructors for the Turtle class that take different parameters:

Turtle Class Constructor Signatures and Parameters

Figure 3: Turtle Class Constructor Signatures and Parameters

exercise Check your understanding

    2-2-4: 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 parameters according to the figure above.
  • Turtle t = new Turtle(50,150);
  • There is no Turtle constructor that takes 2 parameters 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 parameters 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.

    2-2-5: Which of these is the correct signature for a no-argument constructor?

  • public World(int width, int height)
  • This constructor signature defines two arguments: width and height.
  • public World()
  • This constructor signature is correct for a no-argument constructor.
  • public World
  • The constructor signature must include parentheses.
  • public World(int width)
  • This constructor signature defines one argument: width.

2.2.6. 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 use this class library. Then, you can create an object variable called today that uses the default constructor to initialize today to refer to a GregorianCalendar object with 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 (note that January is 0), and day as parameters to set up a specific date. Here’s the same program again but with a new variable myDate that refers to a GregorianCalendar object with the date 1/1/2020.

coding exercise Coding Exercise:

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

Here is the documentation for the GregorianCalendar class which lists two constructors for the class:

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

2.2.7. Formal Parameters, Actual Parameters, and Call by Value

When a constructor like GregorianCalendar(2001,1,1) is called, the formal parameters, (year, month, dayOfMonth), are set to copies of the actual parameters (or arguments), which are (2001,1,1). This is also called call by value which means that copies of the actual parameter values are passed to the constructor. These values are used to initialize the object’s attributes.

Parameter Mapping

Figure 4: Parameter Mapping

exercise Check your understanding

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 object when it is expecting an int. The order of the arguments also matters. If you mix up the year and month in the GregorianCalendar constructor, you will get a completely different date!

    2-2-6: 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.
  • formal parameters
  • A formal parameter is in the constructor's signature.
  • actual parameters
  • A actual parameter (argument) is the value that is passed into the constructor.

    2-2-7: 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.
  • formal parameters
  • A formal parameter is in the constructor's signature.
  • actual parameters
  • A actual parameter (argument) is the value that is passed into the constructor.

In Unit 5, 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.

A Date class showing attributes and constructors

Figure 5: A Date class showing attributes and constructors

exercise Check your understanding

2-2-8: Click on the constructor headers (signatures)Constructors are public and have the same name as the class. Click on the constructor headers which are the first line of the constructors showing their name and parameters.
public class Date {

    private int year;
    private int month;
    private int day;

    public Date() 
        { /** Implementation not shown */ }

    public Date(int year, int month, int day) 
        { /** Implementation not shown */ }

     public void print() 
        { /** Implementation not shown */ }

}

    2-2-9: 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, 2019 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, 2019.
  • Date d = new Date(9,20);
  • There is no Date constructor that takes 2 parameters according to the figure above.
  • Date d = new Date(9,20,2019);
  • The comment for the second constructor in the Date class above says that the first parameter must be the year.
  • Date d = new Date(2019,9,20);
  • This matches the second constructor above with the parameters year, month, day.
  • Date d = new Date(2019,20,9);
  • Make sure the order of the parameters match the constructor signature above.

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 Unit 5 when you write your own classes and constructors.

2.2.8. groupwork Programming Challenge : Debugging

Debug the following code.

2.2.9. Summary

  • Constructors initialize the attributes in newly created objects. They have the same name as the class.

  • A constructor signature is the constructor name followed by the parameter list which is a list of the types of the parameters and the variable names used to refer to them in the constructor.

  • Overloading is when there is more than one constructor. They must differ in the number, type, or order of parameters.

  • New is a keyword that is used to create a new object of a class. The syntax is new ClassName(). It creates a new object of the specified class and calls a constructor.

  • A no-argument constructor is a constructor that doesn’t take any passed in values (arguments).

  • Parameters allow values to be passed to the constructor to initialize the newly created object’s attributes.

  • The parameter list, in the header of a constructor, is a list of the type of the value being passed and a variable name. These variables are called the formal parameters.

  • Actual parameters are the values being passed to a constructor. The formal parameters are set to a copy of the value of the actual parameters.

  • Formal parameters are the specification of the parameters in the constructor header. In Java this is a list of the type and name for each parameter (World(int width, int height).

  • Call by value means that when you pass a value to a constructor or method it passes a copy of the value.

2.2.10. AP Practice

    2-2-10: 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 that takes 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 that takes 2 parameters.
  • II and III
  • II is not correct because there is no Cat constructor that takes 2 parameters.

    2-2-11: 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
Next Section - 2.3. Calling Methods Without Parameters