Oops Try Again Make Sure to Use the Object Constructor
2.2. Creating and Initializing Objects: Constructors¶
A Java class defines what objects of the form 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 grade proper noun ( new Class()
). When this lawmaking executes, it creates a new object of the specified class and calls a constructor, which has the same proper name as the class. For example, new World()
creates and initializes a new object of the Globe
class, and new Turtle(habitat)
creates and initializes a new Turtle
object in the World habitat.
// To create a new object and phone call a constructor write: // ClassName variableName = new ClassName(parameters); Earth habitat = new World (); // create a new Earth object Turtle t = new Turtle ( habitat ); // create a new Turtle object
ii.2.one. Overloading Constructors¶
There can be more one constructor defined in a class. This is called overloading the constructor. At that place is unremarkably a constructor that has no parameters (nothing inside the parentheses following the name of the constructor) similar the World()
constructor above. This is also called the no-argument constructor. The no-statement constructor unremarkably sets the attributes of the object to default values.
There can also be other constructors that take parameters like the Turtle(habitat)
constructor telephone 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
form actually has 2 constructors. One doesn't take any parameters and i takes the world's width and height.

Figure ane: Ii overloaded World constructors¶
Bank check your understanding
- When a constructor takes 1 parameter.
- For a constructor to be overloaded there must be more than one constructor.
- When a constructor takes more one parameter.
- For a constructor to be overloaded there must be more than one constructor.
- When ane constructor is defined in a course.
- For a constructor to exist overloaded there must exist more than than one constructor.
- When more than one constructor is divers in a grade.
- Overloading means that in that location is more than one constructor. The parameter lists must differ in either number, order, or type of parameters.
two-ii-1: Which of these is overloading?
- World west = nada;
- This declares a variable w that refers to a World object, but it doesn't create a Globe object or initialize it.
- Globe w = new World;
- You must include parentheses () to call a constructor.
- World w = new World();
- Apply the new keyword followed by the classname and parentheses to create a new object and phone 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 Earth object?
2.two.two. The Earth Form Constructors¶
The constructor that doesn't accept any parameters, World()
, creates a graphical window with 640x480 pixels. The Earth(int width, int height)
constructor takes 2 integer parameters, and initializes the World
object's width and height to them, for case new Globe(300,400)
creates a 300x400 pixel world.
World world1 = new Globe (); // creates a 640x480 world Earth world2 = new Earth ( 300 , 400 ); // creates a 300x400 world
Note
The turtle world does not use the cartesian coordinate system. The top left corner is (0,0), x increases to the right, and y increases towards the lesser of the page.

Effigy 2: The coordinate (0,0) is at the top left of the Turtle world.¶
2.two.3. The Turtle Class Constructors¶
The Turtle
class also has multiple constructors, although it e'er requires a earth equally a parameter in order to have a identify to draw the turtle. The default location for the turtle is right in the middle of the globe.
At that place is another Turtle
constructor that places the turtle at a certain (x,y) location in the world, for case at the coordinate (fifty, 100) below.
Turtle t1 = new Turtle ( world1 ); Turtle t2 = new Turtle ( 50 , 100 , world1 );
Notation
Detect that the order of the parameters matter. The Turtle
constructor takes (x,y,earth)
as parameters in that social club. If you lot mix up the order of the parameters it volition crusade an error, because the parameters volition non be the data types that it expects. This is i reason why programming languages accept data types – to allow for error-checking.
Check your agreement
- Turtle t = Turtle(world1);
- You lot must employ the new keyword to create a new Turtle.
- Turtle t = new Turtle();
- All turtle constructors take a world equally a parameter.
- Turtle t = new Turtle(world1, 100, 100);
- The society of the parameters matter.
- Turtle t = new Turtle(100, 100, world1);
- This creates a new Turtle object in the passed earth at location (100,100)
2-2-iii: Which of these is valid syntax for creating and initializing a Turtle object in world1?
Coding Practise:
Try changing the code below to create a Earth
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 correct corner? Experiment and find out. What happens if you mix up the social club of the parameters?
(If the code below does not piece of work in your browser, you can as well use the Turtle
code at this repl.it link (refresh page after forking and if it gets stuck) or download the files here to utilise 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 fashion to detect the object in memory. Information technology is similar 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 nothing
means that it doesn't refer to an object withal. You could later create the object and fix 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 lawmaking ( Turtle t2 = new Turtle(world1);
).
World world1 = new Globe (); Turtle t1 = aught ; t1 = new Turtle ( world1 ); // declare and initialize t2 Turtle t2 = new Turtle ( world1 );
2.2.five. Constructor Signatures¶
When you lot use a class that someone has already written for you in a library that you tin import like the Turtle
class above, you lot can look up how to use the constructors and methods in the documentation for that course. The documentation will list the signatures (or headers) of the constructors or methods which volition tell y'all 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 every bit values and their data types.
Constructors are overloaded when at that place are multiple constructors, but the constructors have different signatures. They can differ in the number, blazon, and/or society of parameters. For case, here are two constructors for the Turtle
class that take different parameters:

Effigy 3: Turtle Class Constructor Signatures and Parameters¶
Check your understanding
- Turtle t = new Turtle();
- In that location is no Turtle constructor that takes no parameters according to the effigy above.
- Turtle t = new Turtle(50,150);
- At that place is no Turtle constructor that takes 2 parameters according to the figure to a higher place.
- Turtle t = new Turtle(world1);
- This would initialize the Turtle to the eye of the world, not necessarily coordinates (50,150).
- Turtle t = new Turtle(world1,50,150);
- Make sure the social club of the parameters friction match the constructor signature above.
- Turtle t = new Turtle(50,150,world1);
- This matches the 2d constructor above with the parameters of x, y, and world.
2-2-6: Given the Turtle class in the figure in a higher place 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 superlative)
- This constructor signature defines 2 arguments: width and top.
- public World()
- This constructor signature is right for a no-argument constructor.
- public World
- The constructor signature must include parentheses.
- public World(int width)
- This constructor signature defines one argument: width.
two-2-7: Which of these is the correct signature for a no-argument constructor?
In Unit 5, you lot volition learn to write your own classes. However, if you lot see a class definition on the AP exam, like the one below for a class chosen Date
, you should be able to pick out the attributes (example variables) and the constructors and know how to utilize them.

Figure 4: A Date class showing attributes and constructors¶
Check your understanding
two-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 form Date { individual int year; private int month; private int day; public Appointment() { /** Implementation non shown */ } public Appointment(int yr, int calendar month, int twenty-four hours) { /** Implementation not shown */ } public void print() { /** Implementation not shown */ } }
- Date d = new Date();
- This would initialize the appointment attributes to today'south date according to the constructor comment higher up, which might not be Sept. 20, 2020.
- Date d = new Engagement(9,twenty);
- There is no Date constructor that takes 2 parameters according to the figure higher up.
- Date d = new Date(9,20,2020);
- The annotate for the 2nd constructor in the Date course above says that the first parameter must be the twelvemonth.
- Engagement d = new Appointment(2020,9,20);
- This matches the 2d constructor above with the parameters year, calendar month, mean solar day.
- Date d = new Appointment(2020,twenty,ix);
- Make sure the order of the parameters match the constructor signature higher up.
2-2-9: Given the Appointment
grade in the figure above and assuming that months in the Date
form are numbered starting at 1, which of the following code segments will create a Date
object for the date September xx, 2022 using the correct constructor?
ii.2.half-dozen. Formal and Bodily Parameters¶
When a constructor like Date(2005,ix,1)
is called, the formal parameters, (year, month, day), are ready to copies of the actual parameters (or arguments), which are (2005,9,one). This is call past value which means that copies of the actual parameter values are passed to the constructor. These values are used to initialize the object'south attributes.

Figure 5: Parameter Mapping¶
The blazon of the values beingness passed in as arguments accept 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 twenty-four hours in the Engagement
constructor, you will get a completely different engagement, for instance January 9th (1/9) instead of Sept. 1st (9/1).
Check your understanding
- objects
- Objects have attributes and behavior.
- classes
- A course 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 (statement) is the value that is passed into the constructor.
2-ii-10: In public Globe(int width, int elevation)
what are width
and superlative
?
- 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 (statement) is the value that is passed into the constructor.
2-2-11: In new Globe(150, 200)
what are 150
and 200
?
This lesson introduces a lot of vocabulary, only don't worry if you don't understand everything about classes and constructors still. You will larn more about how this all works in Unit 5 when y'all write your own classes and constructors. And you will come across parameters again with methods in the adjacent lessons.

2.2.7.
Programming Challenge: Custom Turtles¶
Working in pairs, you lot will now wait at a new class chosen CustomTurtle and design some colorful turtles with its constructors.
First, equally 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 form (you volition larn more about inheritance in Unit 9). Withal, information technology has some new constructors with more than parameters to customize a turtle with its trunk color, shell color, width, and height. CustomTurtle has iii constructors:
/** Constructs a CustomTurtle in the middle of the earth */ public CustomTurtle ( World westward ) /** Constructs a CustomTurtle with a specific trunk color, beat out colour, and width and height in the eye of the globe */ public CustomTurtle ( Globe w , Colour body , Color shell , int w , int h ) /** Constructs a CustomTurtle with a specific body colour, beat out colour, and width and top at position (10,y) in the earth */ public CustomTurtle ( int x , int y , Globe due west , Color body , Color shell , int due west , int h )
You will utilise the constructor(s) to create the CustomTurtles below. You can specify colors like Color.red by using the Color class in Coffee.
-
Create a large 150x200 (width 150 and peak 200) CustomTurtle with a light-green body (Color.green) and a blue shell (Colour.blue) at position (150,300)
-
Create a pocket-size 25x50 CustomTurtle with a ruby body and a xanthous shell at position (350,200)
-
Create a CustomTurtle of your own design.
Utilize the CustomTurtle constructors to create the following turtles.
2.two.8. Summary¶
-
Constructors initialize the attributes in newly created objects. They accept the aforementioned proper noun as the class.
-
A constructor signature is the constructor proper 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 than ane 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-statement constructor is a constructor that doesn't take whatever 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 blazon of the value existence passed and a variable proper noun. These variables are called the formal parameters.
-
Bodily parameters are the values being passed to a constructor. The formal parameters are set to a copy of the value of the bodily parameters.
-
Formal parameters are the specification of the parameters in the constructor header. In Java this is a list of the type and proper noun for each parameter (
Earth(int width, int meridian
). -
Call past value ways that when you pass a value to a constructor or method it passes a copy of the value.
ii.ii.9. AP Do¶
- I merely
- I is one of the correct constructors but the second constructor can too exist used.
- I and 2
- Two is non correct because there is no Cat constructor that takes 2 parameters.
- I and Iii
- I and 3 call the correct constructors.
- I, 2, and Three
- II is not correct because there is no Cat constructor that takes ii parameters.
- Two and III
- Ii is not right because there is no True cat constructor that takes 2 parameters.
two-2-14: Consider the following course. Which of the following successfully creates a new Cat object?
public form Cat { private String color ; individual String breed ; individual boolean isHungry ; public True cat () { colour = "unknown" ; brood = "unknown" ; isHungry = imitation ; } public Cat ( String c , Cord b , boolean h ) { color = c ; breed = b ; isHungry = h ; } } I . Cat a = new True cat (); II . True cat b = new True cat ( "Shorthair" , true ); III . String color = "orange" ; boolean hungry = false ; Cat c = new Cat ( color , "Tabby" , hungry );
- Motion-picture show thou = new Movie(eight.0, "Panthera leo King");
- There is no Movie constructor with 2 parameters.
- Movie m = Motion-picture show("Lion Rex", eight.0);
- There is no Movie constructor with two parameters.
- Movie 1000 = new Movie();
- This creates a Movie object but information technology does not have the right title and rating.
- Pic k = new Movie("Lion King", "Disney", viii.0);
- This creates a Film object with the right championship and rating.
- Movie m = new Movie("Panthera leo King");
- This creates a Movie object but it does not take a rating of eight.0.
2-2-15: Consider the following grade. Which of the following code segments will construct a Moving picture object g with a title of "Lion King" and rating of viii.0?
public grade Film { individual String title ; private Cord managing director ; private double rating ; private boolean inTheaters ; public Movie ( String t , String d , double r ) { championship = t ; manager = d ; rating = r ; inTheaters = false ; } public Picture ( String t ) { championship = t ; director = "unknown" ; rating = 0.0 ; inTheaters = fake ; } }
You lot accept attempted of activities on this folio
Source: https://runestone.academy/ns/books/published/csawesome/Unit2-Using-Objects/topic-2-2-constructors.html
Post a Comment for "Oops Try Again Make Sure to Use the Object Constructor"