3.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(habitat)
which are used to 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(habitat)
creates and initializes a new Turtle
object in the World habitat
.
// To create a new object and assign it to a variable write:
//
// ClassName variableName = new ClassName(parameters);
//
// For instance:
World habitat = new World(); // create a new World object
Turtle t = new Turtle(habitat); // create a new Turtle object
3.2.1. Overloading Constructors¶
Like methods, constructors are defined with a list of parameters that determine what arguments they need to be passed. A parameter (sometimes called an formal parameter) is a variable that will hold a value of an argument (sometimes called an actual parameter) passed when the constructor is called. The arguments passed to constructors are used to initialize the attributes of the object.
A constructor that has no parameters is called a no-argument constructor and
is called with nothing inside the parentheses following the name of the
constructor. The call to new World()
above, is an example of a no-argument
constructor.
If a class has a no-argument constructor, that means that has it no
attributes that need to be initialized or all its attributes can be initialized
to meaningful default values values. The World
class is an example of the
latter—the no-argument constructor creates a default sized world.
But not all classes have a no-argument constructor. The Turtle
class, for
instance, doesn’t because the author of the class decided it doesn’t make sense
to create a Turtle
that is not in a particular World
.
There can be more than one constructor defined in a class as long as they differ in what arguments they take. This is called overloading the constructor and allows us provide different ways to create instances of the class. One common pattern is to provide one or more constructors that take arguments for when you want to initialize an object with specific values and also a no-argument constructor for convenience that initializes the object with default values.
The World
class follows this pattern, and has 2 constructors, one which
takes the world’s width and height and another which creates a default-sized
world of 640x480 pixels.
- 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-1: Which of these is overloading?
- 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: Which of these is valid syntax for creating and initializing a World object?
3.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 world does not use the Cartesian coordinate system with (0,0) in in the middle the screen. Instead, (0,0) is at the top left corner of the screen and x increases to the right and y increases towards the bottom of the screen.
Most computer graphics systems use this coordinate system which is a carry over from before computers could display graphics. When computer displays were text based and mostly made by people using left-to-right, top-to-bottom languages like English, it made sense to have the first character appear at the top left and then count columns to the right and lines down.
3.2.3. The Turtle Class Constructors¶
The Turtle
class also has multiple constructors, although it always requires a world as a 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.
- 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 a parameter.
- Turtle t = new Turtle(world1, 100, 100);
- The order of the parameters matter.
- Turtle t = new Turtle(100, 100, world1);
- This creates a new Turtle object in the passed world at location (100,100)
2-2-3: Which of these is valid syntax for creating and initializing a Turtle object in world1?
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 in your browser, you can also use the Turtle
code at this replit.com link (refresh page after forking and if it gets stuck) or download the files here to use in your own IDE.)
3.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. It is like a tracking number that you can use to track the location of a package.
Watch the video 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);
3.2.5. 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 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, 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 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-6: 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)?
- 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-7: Which of these is the correct signature for a no-argument 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.
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 */ } }
- 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 parameters 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 parameter 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 parameters match the constructor signature above.
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, 2020 using the correct constructor?
3.2.6. Formal and Actual Parameters¶
When a constructor like Date(2005,9,1)
is called, the formal parameters, (year, month, day), are set to copies of the actual parameters (or arguments), which are (2005,9,1). This is 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.
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 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).
- 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-10: 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-11: In new World(150, 200)
what are 150
and 200
?
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. And you will see parameters again with methods in the next lessons.
3.2.7. Programming Challenge: Custom Turtles¶
Working in pairs, you will now look at a new class called CustomTurtle and design some colorful turtles with its constructors.
First, as a warm up, do the following debugging exercise.
Debug the following code.
The CustomTurtle class in the ActiveCode below inherits many of its attributes and methods from the Turtle class (you will learn more about inheritance in Unit 9). 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 class in Java.
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)
Create a small 25x50 CustomTurtle with a red body and a yellow shell at position (350,200)
Create a CustomTurtle of your own design.
Use the CustomTurtle constructors to create the following turtles.
3.2.8. 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 isnew 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.
3.2.9. AP Practice¶
- 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-14: 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);
- 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.
2-2-15: 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;
}
}