Lesson_15_Objects3

advertisement
Lesson 15: Objects, Part 3
Constructors
Now you know the two main aspects of a class: fields and methods. There is a third aspect to develop in
this packet: constructors.
A constructor is a part of a class that automatically gives fields their initial values. You have used
constructors frequently – you just didn’t know it. For example, JFrame has two constructors, one which
does not give any fields initial values, and one which gives a JFrame its title. The following two
strategies creating a JFrame with the title “LayoutPractice:”
Long Way: ‘empty’ constructor
JFrame frame = new JFrame();
frame.setTitle("LayoutPractice");
Short Way: send title to constructor
JFrame frame = new JFrame("LayoutPractice");
When constructing a JFrame, whatever comes at the end of the line with the keyword new indicates the
JFrame constructor to use for setting up intial field values. In the long way, above, empty parentheses
come at the end of the line. That means that java should use the JFrame constructor that has no
parameters (and therefore sets no initial field values). In the short way, the line ends with parentheses
around a String. That means that java should use the JFrame constructor that has one parameter, a
String, which will then be set to the title by the constructor.
Using constructors provided by pre-existing java classes comes naturally. More complicated is writing
and using constructors for your own classes. For example, we will return to our simplified JFrame class
from the first object lesson to show how it could have included a constructor for convenience:
1|©Joshua Britton
public class
private
private
private
private
JFrame
{
boolean visible;
int width;
int height;
String title;
public JFrame(String t) {
title = t;
}
Constructor
public void setVisible(boolean b) {
visible = b;
}
public void setSize(int w, int h) {
width = w;
height = h;
}
public void setTitle(String t) {
title = t;
}
Not needed at instantiation,
but kept in case of need to
change title later
public void pack() {
//…
}
}
The declaration of a constructor uses the keyword public, then the name of the class, then any
parameters that the class needs to build an instance. In this example, the constructor needs a String
that will become a JFrame instance’s title.
Do not confuse constructors and methods. They look somewhat similar, but there are two syntactical1
differences.
1.
Constructors do not have a return value
2.
Constructors have the SAME NAME as the class
Here is an example to show you how the java runtime environment (jre) executes code that uses a
constructor:
1
Big Word Alert! Syntax: the specifics regarding how code is written. For example, the VB syntax for a
conditional line of code is “if [condidition] then [statement]”.
2|©Joshua Britton
public class
private
private
private
private
JFrame
{
boolean visible;
int width;
int height;
String title;
2
public JFrame(String t) {
title = t;
}
3
//*********************
//lots of methods here*
//*********************
}
public class
ConstructorDemo
{
public static void main (String [] args) {
JFrame frame = new JFrame("Best Game Ever");
1
//code to create and show gui here
}
}
1. The String “Best Game Ever” is sent to the constructor.
2. The String parameter t temporarily stores “Best Game Ever”.
3. The String field title is assigned to “Best Game Ever”. Now the new JFrame instance’s
title field is set to its initial value without having to call a setTitle method.
Here is another example from our old Snowball class, rewritten yet again, this time with a constructor to
set the initial values of diameter and owner:
3|©Joshua Britton
public class Snowball {
private int diameter;
private String owner;
public Snowball(int d, String o) {
diameter = d;
owner = o;
}
public void setOwner (String n) {
owner = n;
}
Constructor
Not needed because they were
only used to initialize
public void setDiameter(int d) {
diameter = d;
}
public boolean melt(int x) {
diameter -= x;
if (diameter < 1) {
diameter = 0;
return true;
}
else {
return false;
}
}
public void display () {
System.out.println("Imagine you see " + owner +
"'s snowball with a diameter of " +
diameter);
}
}
Here is code from the ConsoleSnowGames main method that contrasts the old, three line procedure for
instantiation and initialization of a Snowball with the one line version that uses a constructor:
4|©Joshua Britton
From ConsoleSnowGames main method:
Old, Long Way
Snowball first = new Snowball();
first.setOwner("Jimmy");
first.setDiameter(getInt(5, 11));
New, Short Way
Snowball first = new Snowball(getInt(5, 11), "Jimmy"));
ASSIGNMENTS
FiringRange2
description: This project should have the same functionality as FiringRange. The only two differences
are:
1. Name the classes Weapon2 and FiringRange2.
2. Use a constructor in Weapon2 to set the original number of bullets in a Weapon2 instance.
Print Weapon2 and FiringRange2 for submission.
EatingContest2
description: This project should have the same functionality as EatingContest. The only two differences
are:
1. Name the classes DonutEater2 and EatingContest2.
2. Use a constructor in DonutEater2 to set the eater’s name in a DonutEater2 instance.
Print DonutEater2 and EatingContest2for submission.
RobotFight (First project of “ConsoleWars”)
We will create several projects in which Robot instances battle and the results are displayed on the
command console. The series is called ConsoleWars, and I have already created some of the files that it
will require. Copy the “ConsoleWars” folder into your java directory. In other words, the folder’s path
should be: “Z:\java\ConsoleWars”. This folder contains many partially written files that you will
complete in a series of Robot projects. Keep all assignments for ConsoleWars projects in this separate
folder.
5|©Joshua Britton
description: In RobotFight, two instances of Robot1 will duel. The project will use two classes: Robot1
and RobotFight. I have already written RobotFight and placed it in the ConsoleWars folder. You will
write the code for Robot1.
Robot1
Create a new class named Robot1 in the ConsoleWars folder. Robot1 will have one field, hitpoints,
a constructor to set the initial value of hitpoints, and two methods that interact with that variable,
getHitpoints and modifyHitpoints.
The constructor and the methods each only need one line of code.
1. Constructor: initialize hitpoints with the value of the parameter.
2. getHitpoints: return the value in hitpoints.
3. modifyHitpoints: increment hitpoints by an integer value. Require the integer as a
parameter of modifyHitpoints.
RobotFight
Once Robot1 compiles successfully, open my RobotFight class. You will see that I have already written
code in the main method. Compile RobotFight, and run it. The output should look similar to the
following:
lin
win
lin
lin
win
win
lin
win
win
win
lin
lin
lin
lin
takes
takes
takes
takes
takes
takes
takes
takes
takes
takes
takes
takes
takes
takes
4
5
2
2
1
5
3
2
3
1
2
2
3
5
points
points
points
points
points
points
points
points
points
points
points
points
points
points
of
of
of
of
of
of
of
of
of
of
of
of
of
of
damage,
damage,
damage,
damage,
damage,
damage,
damage,
damage,
damage,
damage,
damage,
damage,
damage,
damage,
going
going
going
going
going
going
going
going
going
going
going
going
going
going
to
to
to
to
to
to
to
to
to
to
to
to
to
to
16
25
14
12
24
19
9
17
14
13
7
5
2
-3
6|©Joshua Britton
Download