Section1.13Creating 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
Subsection1.13.1The 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.
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.
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.
Turtle t1 = new Turtle(world1);
Turtle t2 = new Turtle(50, 100, world1);
Note1.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.
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?
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.
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);).
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:
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)?
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.
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 */ }}
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?
Subsection1.13.5Arguments, 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.
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).
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.
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β
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)
(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.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.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.
(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.
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);