An Introduction to
Computer Science with Java
Copyright 2013 by C. Herbert, all rights reserved.
Last edited August 21, 2013 by C. Herbert
This document is a draft of a chapter from Computer Science with Java, written by Charles Herbert with the assistance of Craig
Nelson. It is available free of charge for students in Computer Science 111 at Community College of Philadelphia during the Fall
2013 semester. It may not be reproduced or distributed for any other purposes without proper prior permission.
CSCI 111 Chapter 11 Graphics pg. 2
Introduction to
Computer Science with Java
Chapter 11 – Java Graphics
This short chapter describes how programmers can create and manipulate two-dimensional graphics in
Java. It includes creating.
Chapter Learning Outcomes
Upon completion of this chapter students should be able to:
Describe what a graphics processing unit (GPU) is and why GPUs are used
with modern computers.
Describe what the java.awt.Canvas and java.awt.Graphics classes are and
how they are used.
Describe how to do each of the following using the Java Graphics class:
o setting the Color for graphics;
o drawing lines;
o drawing rectangles, and rectangles with rounded corners;
o drawing ovals, circles, and arc of ovals and circles;
o drawing polygons;
o drawing text on the screen.
Describe how to create graphs and charts illustrating business and scientific data.
Create software that uses the Java Graphics class to create figurative and abstract images.
11.1 Overview of Graphics Programming in Java
Graphics programming in Java is done through the use of APIs, including the java.awt.Graphics class and
the Java 2D API that are both part of AWT; Java OpenGL (JOGL), Java 3D (J3D), and Java Advanced
Imaging (JAI), which are official Java APIs; and many third party APIs, such as the Java LightWeight
Game Library (JLWGL). The graphics capabilities in the AWT and the Java OpenGL graphics libraries are
by far the most commonly used.
In this chapter we will focus on creating simple graphics and concepts of graphics programming using
the graphics classes included in AWT, which will allow us to create and manipulate simple graphic
images that can be displayed using the same containers as those used for Swing components.
The graphics capabilities in AWT should work equally as well on Windows, Mac and Linux-based
systems, although specialized coding for certain devices and unique hardware configurations may
require the use of specialized APIs.
CSCI 111 Chapter 11 Graphics pg. 3
Generally, instructions in Java, as in any programming language are fed through the operating system to
the computer’s hardware. In the case of graphics programming, an additional component is often
present – a graphics processing unit. A graphics processing unit (GPU), often called a graphics
accelerator, is a specialized processing unit for rendering high quality im ...
An Introduction to Computer Science with Java .docx
1. An Introduction to
Computer Science with Java
Copyright 2013 by C. Herbert, all rights reserved.
Last edited August 21, 2013 by C. Herbert
This document is a draft of a chapter from Computer Science
with Java, written by Charles Herbert with the assistance of
Craig
Nelson. It is available free of charge for students in Computer
Science 111 at Community College of Philadelphia during the
Fall
2013 semester. It may not be reproduced or distributed for any
other purposes without proper prior permission.
CSCI 111 Chapter 11 Graphics pg. 2
Introduction to
2. Computer Science with Java
Chapter 11 – Java Graphics
This short chapter describes how programmers can create and
manipulate two-dimensional graphics in
Java. It includes creating.
Chapter Learning Outcomes
Upon completion of this chapter students should be able to:
) is and why
GPUs are used
with modern computers.
classes are and
how they are used.
Graphics class:
o setting the Color for graphics;
o drawing lines;
o drawing rectangles, and rectangles with rounded corners;
o drawing ovals, circles, and arc of ovals and circles;
o drawing polygons;
o drawing text on the screen.
and scientific data.
3. figurative and abstract images.
11.1 Overview of Graphics Programming in Java
Graphics programming in Java is done through the use of APIs,
including the java.awt.Graphics class and
the Java 2D API that are both part of AWT; Java OpenGL
(JOGL), Java 3D (J3D), and Java Advanced
Imaging (JAI), which are official Java APIs; and many third
party APIs, such as the Java LightWeight
Game Library (JLWGL). The graphics capabilities in the AWT
and the Java OpenGL graphics libraries are
by far the most commonly used.
In this chapter we will focus on creating simple graphics and
concepts of graphics programming using
the graphics classes included in AWT, which will allow us to
create and manipulate simple graphic
images that can be displayed using the same containers as those
used for Swing components.
The graphics capabilities in AWT should work equally as well
on Windows, Mac and Linux-based
systems, although specialized coding for certain devices and
unique hardware configurations may
require the use of specialized APIs.
4. CSCI 111 Chapter 11 Graphics pg. 3
Generally, instructions in Java, as in any programming language
are fed through the operating system to
the computer’s hardware. In the case of graphics programming,
an additional component is often
present – a graphics processing unit. A graphics processing unit
(GPU), often called a graphics
accelerator, is a specialized processing unit for rendering high
quality images and video on a computer
screen. GPUs are often accompanied by additional specialized
graphics memory on a board that can be
added to a computer. Such boards are known as graphics cards.
GPU’s are used because of the massive amount of data involved
in imaging, especially video. A typical
HD television image has between 900.000 and 2.1 million pixels
per frame, with 3 or 4 bytes needed to
store each pixel. At 30 frames per second, the highest quality
raw video data would need a bandwidth in
the neighborhood of 30 billion bytes per second. Many special
techniques are used to reduce and
compress this data. The Society of Motion Picture and
Television Engineers (SMPTE ) has developed the
5. HD-SDI standard for broadcast HD video, which requires a
bandwidth of 1.485 Gbits/Sec.
The image below shows a modern ATI Raedon HD GPU, which
communicates with the CPU and 2 Gb of
graphics memory, and can control several display monitors. Its
components function as follows:
GPU for 3D video graphics and
can also perform 2D graphics.
still images.
U.
with the graphics memory.
communication between the memory
and the video processing engine.
units are proprietary circuits that
manipulate images moving from
6. video memory to the screen.
pipelines that translate graphic
images to coordinate system for the
hardware. They allow for parallel
processing of data moving to display
screens.
Even still images can require a lot of memory and processing
power. A 3-megapixel image from a
cellphone camera can use a megabyte of memory – which is as
much as 8 minutes of MP3 quality sound
or 64 thousand characters of Unicode text, roughly a 50 page
document.
CSCI 111 Chapter 11 Graphics pg. 4
11.2 Using the java.awt.Canvas and java.awt.Graphics Classes
The most commonly used classes for graphics programming in
Java are those found in AWT. They are
often used in conjunction with Swing components in GUI
programming. We will use two of those
7. classes: the java.awt.Canvas class and the java.awt.Graphics
class.
The Graphics class draws shapes on top of existing GUI
components, such as drawing an image on a
button. A Canvas class object in Java is a component
representing a blank window on which we may
draw shapes. We can also read user input on a Canvas, such as
the location of the screen pointer when
someone clicks a mouse button.
The paint() method is the method that draws on a component,
but the paint() method in the Canvas
class leaves the Canvas blank. We can create our own
customized Canvas as a subclass of the Canvas
class, then draw on our Canvas object by defining the
paint()method for our class.
Inside the paint() method we will use methods from the
java.awt.Graphics class to draw on our Canvas.
The java.awt.Graphics class contains many features for drawing
images. Quoting from Oracle’s Java
Tutorials Website
1
: “The Java 2D™ API is powerful and complex. However, the
vast majority of uses for
the Java 2D API utilize a small subset of its capabilities
8. encapsulated in the java.awt.Graphics class”.
Here is an example of how this works. The following code
creates a sub class of Canvas called MyCanvas,
with three simple rectangles. The paint() method in the
MyCanvas class will draw three rectangles on
the canvas, the second of which is a filled rectangle. The
objects are drawn in the order on which the
code to do so appears in method, so the second rectangle is on
top of the first, and the third in on top of
the second. The main() method creates and displays a JFrame
object containing a MyCanvas object.
/* ThreeRectangles.java
* last edited Nov. 15, 2013 by C.Herbert
*
* This code demonstrates the creation of a canvas subclass for
drawing
* by overriding the paint method() in the subclass.
*
* The main() method displays the canvas with our graphihcs in
a JFrame.
*
*
9. */
package threerectangles;
import java.awt.*;
import javax.swing.*;
public class ThreeRectangles {
public static void main(String[] args)
{
// create a MyCanvas object
1
The java graphics tutorials are available online at:
http://docs.oracle.com/javase/tutorial/2d/basic2d/index.html
They are
useful, but may be difficult to use for beginning programmers.
http://docs.oracle.com/javase/tutorial/2d/basic2d/index.html
CSCI 111 Chapter 11 Graphics pg. 5
MyCanvas canvas1 = new MyCanvas();
10. // set up a JFrame tpo hold the canvas
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setLocation(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add the canvas to the frame as a content panel
frame.getContentPane().add(canvas1);
frame.setVisible(true);
} // end main()
} // end class ThreeRectangles
class MyCanvas extends Canvas
{
public MyCanvas()
{
11. } // end MyCanvas() constructor
public void paint(Graphics graphics)
// note: the graphics parameter is required as an artifact from
inheritance
{
graphics.setColor(Color.red);
graphics.drawRect(10, 10, 110, 110);
graphics.setColor(Color.green);
graphics.fillRect(35, 35, 135, 135);
graphics.setColor(Color.blue);
graphics.drawRect(60, 60, 160, 160);
} // end paint()
} // end class MyCanvas
In summary, methods from the Graphics class
(java.awt.Graphics) such as the drawRect() method, can
be used to draw on a GUI component. The Canvas class
(java.awt.Canvas) is a component that creates a
12. blank canvas just for such drawing. The paint method() in the
Canvas class leaves the canvas blank. We
can create our own canvas as a sub-class of the Canvas class
and draw on the canvas by overriding the
paint() method. The canvas can then be displayed by placing in
a container, such as a JFrame object, and
making the container visible.
11.3 Using Methods from the Graphics Class
In this section we will see how to draw with some of the most
commonly used methods from the
Graphics class, including methods for:
the Color for graphics;
CSCI 111 Chapter 11 Graphics pg. 6
We will start by looking at the coordinate system for onscreen
13. graphics.
Onscreen Coordinates
Most computer screens use an inverted Cartesian coordinate
system A Cartesian coordinate system –
named for its inventor René Descartes – is a standard two-
dimensional rectangular coordinate system
with an x values that increase to the right and y values that
increase upward. The two-dimensional
system is bisected horizontally by a vertical y-axis where x =0
and a horizontal x-axis where y=0, as
shown below. Points are located with an ordered pair of x and y
coordinates – (x,y).
CSCI 111 Chapter 11 Graphics pg. 7
An inverted Cartesian coordinate system is the same as a
14. Cartesian coordinate system, except that the
Y-axis values increase with movement downward. The first
computer screens that appeared in the
middle of the Twentieth Century displayed text in lines across
the screen with one line below another
starting from the top left corner of the screen. The text
coordinates were measured from the top left
corner across and down.
Graphics on computer monitors followed this convention, with
the origin in the top left corner of the
screen, the x-coordinate increasing across the screen from left
to right, and the y-coordinate increasing
down the screen from top to bottom. Thus the name inverted
Cartesian coordinate system, in which the
y coordinate goes up as we move down the screen.
In containers such as JFrames, the same inverted Cartesian
coordinate system is used. Points are
referenced by (x,y) ordered pairs, with the origin in the top
right corner of the frame. The x coordinate
increase to the right and the y coordinate increase downward.
The following sections describe some of the most commonly
used methods from the Graphics class. The
methods would be used in the paint method to draw on a
15. component, such as a class that extends the
Canvas class, as in the example on pages 4 and 5 above.
In these examples, instance is the name of the instance of the
graphics class. All coordinates are integer
values of data type int.
Drawing Lines
drawLine(int x1, int y1, int x2, int y2);
draws a line between the points (x1, y1)
and (x2, y2).
Drawing Rectangles
drawRect(int x, int y, int width, int height) draws the outline of
a rectangle of the specified width and
height with the top left corner at point (x,y). The bottom right
corner will be at point(x+width, y+height.
To draw a square, specify equal values for width and height.
fillRect(int x, int y, int width, int height) draws a filled
rectangle.
CSCI 111 Chapter 11 Graphics pg. 8
16. Rectangles with Rounded Corners
drawRoundRect(int x, int y, int width, int height, int arcWidth,
int arcHeight) draws an outline of
rectangle with rounded-corners. The arcWidth and arcHeight
parameters set the horizontal and vertical
diameter of the arc used for the corners of the rectangle.
fillRoundRect(int x, int y, int width, int height, int arcWidth,
int arcHeight) draws a filled rectangle.
The example below shows a standard rectangle and three
rectangles with rounded corners, each drawn
with different parameters.
Drawing Ovals and Circles
drawOval(int x, int y, int width, int height) draws an outline of
an oval within a rectangular area whose
top left corner is at point (x, y) and whose bottom right corner
is at point (x+width, y+height).
To draw a circle, specify equal values for width and height.
The diameter of the circle will be equal to
the value used for width and height; the radius will be half that
value. The center point of an oval or a
circle will be at coordinates (x+(width/2), y+(height/2)).
17. fillOval(int x, int y, int width, int height) draws a filled oval.
The example below shows three ovals, each drawn with
different parameters.
CSCI 111 Chapter 11 Graphics pg. 9
Drawing Arcs of Ovals and Circles
drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle) draws an outline of arc, which is
a segment of the perimeter of an oval where:
whose top left corner is at point (x, y)
and whose bottom right corner is at point (x+width, y+height);
extends for arcAngle degrees;
and measurement moves
18. counterclockwise around the oval for 360 degrees, as shown in
the diagram below.
fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle) draws a filled segment of an oval
defined by the specified arc.
The code below draws the arcs shown, each drawn with
different parameters.
CSCI 111 Chapter 11 Graphics pg. 10
Drawing Polygons
drawPolygon(int[] xPoints, int[] yPoints, int n) draws a polygon
with n vertex points defined by an array
of x coordinates, and an array y coordinates.
fillPolygon(int[] xPoints, int[] yPoints, int nPoints) draws a
filled polygon.
Drawing Text
drawString(String str, int x, int y) draws text specified by given
String, starting with the baseline of the
leftmost character at point (x,y).
19. The Color and Font of the text can be specified using the
setColor()and SetFont() methods for
components, as discussed in chapter 7, section 7.9.
The example below shows code to draw a text message
identifying a previously drawn shape.
CSCI 111 Chapter 11 Graphics pg. 11
Drawing Images from a Data File
drawImage(Image img, int x, int y, ImageObserver observer)
draws the image img with its top left
corner at the point (x,y). observer can be left null. Two lines
are required to create an image from a file
and display the image:
Image name = new ImageIcon( “filename” ).getImage();
instance.drawImage(name, x, y,null);
The first line will create an image with the name name from the
file identified by the String “filename”,
where “filename” may be a local or full context name of an
image file. The second line will draw the
20. image on the screen. This technique works with JPEG, PNG,
GIF, BMP and WBMP file types, although
there may be some timing issues loading animated GIF files as
Java Image class objects.
The following shows an example of this:
11.4 Programming Examples – a Histogram
A histogram is a graphic representation of data, also known as a
bar chart. In this example we will look
at a histogram created using java’s graphics class.
The first step in drawing any graphic image is to design the
image. We wish to create a bar chart
showing enrollments in Computer Science courses at
Community College of Philadelphia in the Fall
semester for four years. Here is the data:
year students
2010 ................. 106
2011 ................. 105
2012 ................. 142
2013 ................. 324
21. Sections were added in 2012 and again in 2013, increasing
enrollment.
A sample Netbeans project named DrawDemo that demonstrates
the commands in
this section is included in the files for this chapter.
CSCI 111 Chapter 11 Graphics pg. 12
We wish to create a histogram that looks something like this
one, created in Microsoft Excel:
We need to create text labels, rectangles to represent the data,
and the lines on the chart. The size of
each rectangle is related to the magnitude of the data. The
maximum data value is 324. We will use a
slightly higher number, 350, for the scale on our graph – 0 to
350. Each of our bars will be proportional
in size to 350.
year students
2010 ................. 106 106/350 = .303
2011 ................. 105 105/350 = .300
2012 ................. 142 142/350 = .406
22. 2013 ................. 324 324/350 = .926
Our scale for the graph will be 20 pixels for each 50 units of
data. This means that 350 units on the y-
axis will take up 140 pixels. They will be drawn up from the
bottom, with a baseline of y = 200.
The bars will be 20 pixels wide, with 20 pixels between bars.
We will also put a small picture of the Computer Science logo
in the upper left corner of the window.
The program needs to do the following:
1. place logo in corner
2. place title at top of chart
3. in a loop, place the horizontal lines and the labels for the
lines 50, 100, 150, etc. up to 350.
4. in a loop, draw the bars – every 40 units in the x direction, 20
units wide, with the height of the
filled rectangle for the bar determined by the enrollment value
for that bar.
CSCI 111 Chapter 11 Graphics pg. 13
The program has some math to calculate where things should be
drawn on the canvas, and to adjust
23. how the labels line up with lines and bars on the chart.
Here is what the finished histogram looks like:
The lines, labels and filled rectangles for the bars are each
drawn using standard Graphics class
statements. The difficult part is laying the design of the chart,
then doing a bit of tedious math to figure
out the coordinates for drawing the objects. The inverted
Cartesian screen coordinates make things a
bit more tedious. Using loops to draw the lines and the bars
saves some work.
The code to draw this histogram is included in the NetBeans
project Histogram, included with the files
for this chapter. Obviously, it is easier to use software such as
Excel to draw charts and graphs. This
project is included as an object of study to learn more about
using Graphics class objects in Java.
11.5 Programming Example – a Pie Chart
A pie chart, like the one shown below, depicts how each number
in a set of numbers is part of the whole
in proportion to the other parts. Pie charts can be created in
Java by using the fillArc()method.
Adjacent filled arcs are drawn for each value with the length of
the arc proportional to the size of the
24. value for that arc.
For a pie chart, we need to know where each arc starts and the
size of the arc in degrees. The total pie
chart will be 360 degrees. First we calculate the sum of the
values. Then, The size of the arc (in degrees)
that corresponds to each value will be (value* 360/sum). The
first arc will start at zero degrees. For each
slice of the pie chart, we will calculate the size of the arc, draw
the arc, then use the size to calculate the
starting angle for the next arc.
CSCI 111 Chapter 11 Graphics pg. 14
Each slice of the pie chart will have a value, a label for that
value, and a color. The label and value can
be read in from a data file or entered by a user. The colors can
be defined in the program.
We will also need a title for our pie chart. In the example
below, we will read data from a file that has:
the title of the chart on the first line, then sets of lines – each
having a line with a label, followed by a
line with the value that matches the label.
25. In addition to drawing the pie chart, we will draw a legend that
has a square with the same color as the
slice, along with the label and value for that color.
The following algorithm shows how to do this:
1. read the data file:
a. first, read the title
b. then in a loop,
c. Load the labels and values for each slice into arrays. We will
put the labels in the array
sliceLabel[]. We will put the values in the array sliceValue[].
Alternatively, this could be
done by letting the user enter the data.
d. As we load the values, we will also calculate the sum of the
values.
2. We will also need a color for each slice. We will call the
array sliceColor[].We can hardcode these
colors into our program. Color[] sliceColor = { Color.RED,
Color.BLUE, Color.GREEN,
Color.MAGENTA, Color. PINK, Color. GRAY, Color. CYAN,
Color. ORANGE} This array of colors can
handle up to 8 slices in the pie chart. Alternatively, we could
define our own Color for any slice,
26. by using a Color constructor with RGB values, such as new
Color(128,0, 255).
3. Draw the Title for the chart.
4. Draw the body of the chart. We need to keep track of where
each arc starts and the size of the
arc in degrees. We will initialize the starting angle to be 0
degrees. The total pie chart will be
CSCI 111 Chapter 11 Graphics pg. 15
360 degrees. The size of the arc (in degrees) corresponding to
each value will be
(sliceValue [i] * 360/sum). In a for loop for the number of
slices:
a. Calculate the size of the arc: (size = (a[i] * 360/sum) *
360)
b. Set the color for arc i to be sliceColor[i].
c. Draw the arc: fillArc(x, y, width, height, start, size)
d. Draw the square in the legend for this slice.
e. Add the label and value next to the square.
f. Calculate the value of start for the next slice: start = start +
size.
When the loop is finished, the chart will be done.
27. The code for this is included as the NetBeans project PieChart
in the files for this chapter. It draws the
pie chart above, showing the popular vote for the Dubious
Presidential Election of 1824, which resulted
in the House of Representatives selecting the president in what
has come to be known as the “Corrupt
Bargain”. You can draw pie charts for different data simply by
editing the PieChartData.txt file included
with the project.
Data about each slice of the pie can be stored in parallel arrays,
or as properties of a Slice object. The
example for this uses parallel arrays.
11.6 Programming Example – Trigonometric Functions
It is much easier to draw graphs of functions than it is to draw
histograms or pie charts. We simply need
to have a loop that goes through 360 degrees, calculates the
function for each degree, then draws the
function on the screen. However, some factors are necessary to
convert the value of the function for
each degree into coordinates on the screen.
For example, the sine of an angle varies from +1 to -1. If we
wish to plot the point (x,y) where x is the
28. angle and y is sine(x), we need to use a few factors to enlarge
the graph the image on the screen.
The following pseudocode shows a short algorithm for plotting
a sine curve. The value of the sine
function is multiplied by 100, giving us the range -100 to +100,
and it is added to 200 to position it on
the screen:
for(x =0.0; x <=360.0; x++)
{
y = 100.0 * Math.sin( Math.toRadians(x) );
plot (x,y)
}
The flowing image was drawn in a similar fashion, but instead
of plotting each point, a line was drawn
from each point on the curve to the next. The code for this is in
the NetBeans project SineCurve,
included with the files for this chapter. It uses several factors to
line things up on the screen, and adds a
few labels, as described in the comments in the source code.
CSCI 111 Chapter 11 Graphics pg. 16
29. We can also convert the drawing to polar coordinates using
parametric equations, and draw what is
known as a cosine rose. Basically, a cosine curve is wrapped
around a circle.
The image below shows this. The code for this is included in
the Netbeans project CosineRose. It starts
with a JOptionPane dialog box to ask the user for a factor that
will alter the image. The code uses a time
delay with try-catch blocks for exception handling, which is
described in the next chapter.
CSCI 111 Chapter 11 Graphics pg. 17
11.7 Programming Example – Abstract Computer Graphics
Using the graphics commands shown in this chapter and a little
creativity, it is fairly easy to create some
original computer artwork. Such as the example below:
Figurative art or abstract art can be drawn using various
graphics commands. Figurative art represents
30. things form the physical world. Abstract art represents more
abstract concepts. The Random Rectangles
image above is abstract; The Bedroom Window below is
figurative.
The art can also be dynamic, which means putting time delays
in the program to allow the user to see
the art being drawn or see the art changing while the program
runs.
Some of the examples shown here are abstract, dynamic art. To
see them in action run the program
included in the NetBeans projects RandomRectangles and
CirclePatterns included with this chapter.
CSCI 111 Chapter 11 Graphics pg. 18
Netbeans projects named RandomRoses and RandomCards are
also included with the files for this
chapter.
Warning: Some dynamic art programs flash on the screen and
could cause problems for people prone to
seizures, such as the CirclePatterns program.
31. CSCI 111 Chapter 11 Graphics pg. 19
Chapter Review
Section 1 of this chapter describes software and hardware used
for computer graphics including what a
graphics processing unit (GPU) is and why GPUs are used with
modern computers.
Section 2 describes the use of the java.awt.Canvas and
java.awt.Graphics classes
Section 3 is a long section describing how to work with of some
of the most commonly used drawing
methods in the Graphics class. It includes a discussion of
inverted Cartesian coordinates.
Section 4 shows an example of the Graphics class to create a
histogram. The process of laying out the
design for the histogram can be a tedious process. so students
are not expected to do this as part of this
class.
Section 5 shows an example using the Graphics class to create a
pie chart. The software included with
this chapter has a program to draw a pie chart from a data file.
Students can draw different pie charts
by changing the data file.
32. Section 6 demonstrates how to use the Graphics class to graph a
trigonometric function. It also has a
sample program that draws a cosine rose.
Section 7 discusses using the Graphics class to create abstract
and figurative computer artwork,
including still images and dynamic art.
Chapter Questions
1. What is a GPU? Why is it used for computer graphics?
2. What is the Canvas class in Java? Why is it used to in
conjunction with the Graphics class?
3. What is coordinate system is used for most computer
graphics? How does it compare to a Cartesian
coordinate system? Historically, how did this come to be used
for computer graphics?
4. What coordinates must be specified to draw a rectangle using
the drawrectangle() method?
5. How can we draw a filled rectangle using methods from the
Java Graphics class?
6. How can we draw a circle using methods from the Java
Graphics class? What about a triangle or
hexagon?
7. What is the system of measurement and direction for drawing
arcs of circle and ovals using the
33. drawArc() method?
8. How can we draw text on a Canvas using methods from the
Graphics class? How can we affect the
appearance of the text?
9. What is the difference between figurative and abstract
images?
10. What is the meaning of the term dynamic art with reference
to computer generated images?
CSCI 111 Chapter 11 Graphics pg. 20
Chapter Exercise
Your task for this chapter is to write a Java program using the
Java Graphics class to create an example
of a computer generated image. This is an opportunity for you
to explore computer graphics and
exercise some individual creativity.
You should submit well-documented code, along with a lab
report describing your work. What
happened in the process of exploration and design for your
project? How does your code work? How did
34. you use other features of Java, such as branching routines or
loops in your work? Tell us about the
thoughts behind your finished work. What influenced your
work?
Your work can be as simple or as complex as you would like,
but be careful about taking on something
that will be enormously time consuming. If you decide to work
on figurative art, It might help to start
with a single idea or concept, such as snowfall in the city, or
along the Schuylkill. Figurative art can also
be static or dynamic. Imagine how, for example, the Bedroom
Window example at the end of this
chapter could be subtly dynamic.
Your finished image for this project should be suitable for a
general audience.
This assignment will be the final project for our class, although
you will have a short assignment
regarding Exceptions.
CSCI 111 Chapter 11 Graphics pg. 21
Contents
Chapter 11 – Java Graphics
35. ...............................................................................................
............................ 2
Chapter Learning Outcomes
...............................................................................................
...................... 2
11.1 Overview of Graphics Programming in Java
................................................................................. 2
11.2 Using the java.awt.Canvas and java.awt.Graphics Classes
........................................................ 4
11.3 Using Methods from the Graphics Class
....................................................................................... 5
Onscreen
Coordinates.............................................................................
.............................................. 6
Drawing Lines
...............................................................................................
......................................... 7
Drawing Rectangles
...............................................................................................
................................ 7
Rectangles with Rounded Corners
...............................................................................................
......... 8
Ovals and Circles
...............................................................................................
.................................... 8
36. Drawing Arcs of Ovals and Circles
...............................................................................................
.......... 9
Drawing Polygons
...............................................................................................
................................. 10
Drawing Text
...............................................................................................
........................................ 10
Drawing Images from a Data File
...............................................................................................
......... 11
11.4 Programming Examples – a Histogram
....................................................................................... 11
11.5 Programming Example – a Pie Chart
...........................................................................................
13
11.6 Programming Example – Trigonometric Functions
..................................................................... 15
11.7 Programming Example – Abstract Computer Graphics
.............................................................. 17
Chapter Review
...............................................................................................
........................................ 19
Chapter Questions
...............................................................................................
................................... 19
37. Chapter Exercise
...............................................................................................
...................................... 20
An Introduction to
Computer Science with Java
Copyright 2013, 2019 by C. Herbert, all rights reserved.
Last edited November 22, 2019 by C. Herbert
This document is a draft of a chapter from Computer Science
with Java, written by Charles Herbert with the assistance of
Craig
Nelson. It is available free of charge for students in Computer
Science 111 at Community College of Philadelphia during the
Fall
2019 semester. It may not be reproduced or distributed for any
other purposes without proper prior permission.
Chapter 9 – Classes and Objects in Java
Contents
Chapter 9 – Classes and Objects in Java
...............................................................................................
........ 2
38. Chapter Learning Outcomes
...............................................................................................
...................... 2
9.1 Defining Classes of Objects in Java
...............................................................................................
2
9.2 Organizing Class Declarations in Java
........................................................................................... 6
Independent, De-Coupled Class Files
...............................................................................................
..... 6
Independent Classes in a Single Java
File.........................................................................................
..... 8
Nested Classes in a Single Java File
...............................................................................................
........ 8
Lab 9A – Creating multiple independent class files in IntelliJ
IDEA .......................................................... 9
9.3 Use of the Java Keyword this
...............................................................................................
....... 15
9.4 Example – Array of Objects: Monopoly Board Squares
.............................................................. 16
9.5 Abstract Methods, Abstract Classes, and Java Interfaces
........................................................... 23
39. Abstract Classes
...............................................................................................
................................... 23
Example of an Abstract Class – the Shape Class
................................................................................. 23
UML Diagrams for Inheritance and Abstract Classes
.......................................................................... 26
Java
Interfaces................................................................................
..................................................... 27
Interfaces in UML diagrams
...............................................................................................
................. 29
Java’s Comparable Interface
...............................................................................................
................ 29
Example – implementing Java’s Comparable Interface
.................................................................... 30
9.6 Copying Objects
...............................................................................................
........................... 32
A Copy Constructor in Java
...................................................................................... .........
.................. 33
Chapter Review
...............................................................................................
........................................ 34
40. Chapter Questions
...............................................................................................
................................... 34
Chapter Exercise
...............................................................................................
...................................... 35
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 2
Introduction to
Computer Science with Java
Chapter 9 – Classes and Objects in Java
This chapter describes how we can create our own classes in
Java. It includes creating classes of objects,
passing objects as parameters, use of the Java keyword this, and
implementing interfaces.
Chapter Learning Outcomes
Upon completion of this chapter students should be able to:
• Create a class of objects in Java as a collection of properties
and methods
that manipulate the properties.
• Create constructor, accessor, mutator, utility, and static
methods within Java
41. classes.
• Use objects of the students’ own creation in Java methods in
other classes.
• Describe the concept of an inner Class and create Java code
that uses inner
classes.
• Describe the use of the Java keyword this and properly use it
in Java
methods.
• Create and manipulate an array of objects in Java.
• Describe the concept of a Java interface and a Java abstract
class, the
purpose of the comparable interface and compareTo() method,
and
demonstrate their use in a Java class.
9.1 Defining Classes of Objects in Java
NOTE: Chapter 8 contains an introduction to the concepts of
object-oriented programming and should be
completed before working with this chapter.
The code that defines a class in Java is called a class
declaration, but it is also known as a class
42. definition. Class declarations in Java start with the keyword
class, then the name of the class, followed
by a set of braces enclosing the declarations for the properties
and methods in the class. Remember that
the Java naming convention is to start a class name with an
uppercase letter.
class ClassName {
// declare properties
// declare methods – with constructors first
) // end class ClassName
If a class is to be a public class, its name should preceded by
the visibility indicator public. Only one class
in each *.Java file may be public. If no visibility modifier is
used, then the class is package-private, and is
only accessible from within the package.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 3
Note about executable classes:
If a Java file has a main() method, it must be in a public class.
The public class then becomes an executable
class because of the presence of a main() method. The main()
method is a static method, and such a class is
43. an executable Java project class, in which all other methods in
the class are often static methods called from
the main() method. Such a class is not a class used to define
instances of objects, but an executable class
used to start software.
Usually the properties of an object are declared first in a class
declaration, followed by the methods.
Putting the set of property declarations together at the top of a
class declaration works like a data
dictionary, making it easier for someone reading a class
declaration to know what the properties of the
object are.
The constructors should be listed before other methods. As with
properties, this makes it easier for
someone reading the method to find them.
Example – Java Class Declaration
The following code shows a class declaration in Java for a Book
class of objects:
public class Book
{
// declare properties
44. private String isbn;
private String title;
private String subject;
private double price;
// constructor methods ******************************
public Book()
{
} // end Book()
public Book(String number, String name)
{
isbn = number;
title = name;
} // end Book(String number, String name)
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 4
// accessor methods *******************************
45. public String getTitle()
{
return title;
} // end getTitle()
public String getISBN()
{
return isbn;
} // end getISBN()
public String getSubject()
{
return subject;
} // end getSubject()
public double getPrice()
{
return price;
} // end getPrice()
46. // mutator methods ******************************
public void setTitle(String name)
{
title = name;
} // end setTitle()
public void setISBN(String number)
{
isbn = number;
} // end setISBN()
public void setSubject(String sub)
{
subject = sub;
} // end setSubject()
public void setPrice(double value)
{
price = value;
47. } // end setPrice()
// method to return information about the book as a String
public String toString()
{
return ("Title: " + title + "ISBN: " + isbn);
} // end to String()
} // end class Book
The Book class is properly encapsulated by making all of its
properties private. Only the public methods
may be used from outside of the class.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 5
The Book class has two constructors, a default constructor and a
constructor with two parameters,
number and name. A default constructor in Java is a
constructor with no parameters. Such a
constructor is often also a null constructor or a nullary
constructor. (Nullary is a term from mathematics
48. that indicates a function or operation with no operands.
Compare it to unary (with one operand) and
binary (with two operands). A null constructor sets up the
proper memory storage space for an instance
of an object, but the object's properties have null values – they
are empty.
A null constructor is simply a constructor with no code in the
method. Consider the following code,
which uses the default null constructor to create an instance of a
book:
Book myBook = new Book();
a new Book object with null values in its properties is created.
The variable myBook will contain a
reference to the new Book object.
A constructor whose declaration contains parameters is an
initializing constructor. It will create an
instance of an object with some or all the properties initialized,
depending on how the method is
defined.
Consider the following code which uses the initializing
constructor in the Book class to create an
instance of a book:
49. Book myBook = new Book("978-02-62031417", "Introduction to
Algorithms");
a new Book object with some initial values in its properties is
created. The variable myBook will contain
a reference to the new Book object. (This data is for a real
book, By Cormen, Leirson and Rivest, an is an
important work in Computer Science.)
These two methods with the same name but with different
parameters are an example of parametric
polymorphism, discussed in the previous chapter.
Each Java class that defines instance of an object must have a
constructor. If a class declaration in Java
does not contain any constructors, then the compiler will add a
default null constructor with an empty
method body.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 6
In the Book class example, the standard accessor methods
follow the constructor, and then the mutator
methods follow the accessors. There are no static methods or
properties. Static methods and properties
50. are normally listed first in the declarations of properties and
methods, but static methods are not often
used in classes that create instances of a class of objects.
The toString method could also be considered an accessor
method, since it returns information from the
properties of an object. It is a good programming practice to
include a toString() method for a class of
objects that returns identifying information about an object as a
String.
9.2 Organizing Class Declarations in Java
Java provides several different ways to organize and access
declarations for new classes of objects. In
this section we will examine three of those ways:
• independent, de-coupled class files with each class declaration
in its own file
• multiple classes in a single *.java file,
• inner classes, with one class declared inside another class.
Independent, De-Coupled Class Files
Unless there is a special reason to do otherwise, each class
should be
declared in its own file, creating independent de-coupled class
files. This is
51. the preferred approach to declaring objects in Java, as in many
object-
oriented programming languages.
Java source code should be contained in a text file ending with
the
extension “.java”. If the code contains a class with an
executable main()
method, it is an executable Java project file. However, most
classes in
object-oriented programming are not executable classes, they
are classes
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 7
that define objects to be used by other software. The Book
class in section 1 of this chapter is an
example – it is not executable and cannot be run by itself as a
program. It is used in conjunction with
other software to create instances of a book object.
Class files should have the same name as the class they are
defining -- the Book class is in the file
Book.java.
For true object-oriented programming –beyond trivial examples
52. like those found at the beginning of a
Java textbook or a Java language tutorial, we need both properly
defined classes of objects and a public
class with a main() method that allows us to execute our code.
Here is an example of an executable class that uses the book
class to create an instance of a book
object. It is the in the file BookProject.java from a project
named BookProject.
/* BookProject.java
* This file contains the excutable class for a project
* demonstrating the use of a Book object
* last edited November 20, 2019 by C. Herbert
* The file declaring the Book class must be visible to this Main
class.
*/
package BookProject;
public class Main {
public static void main(String[] args) {
53. // create an instance of the book class of objects
// note: this is a real book important in the history of
Computer Science
Book myBook = new Book("978-02-62031417","Introduction
To Algorithms");
// add a subject and a price
myBook.setSubject("Computer Science");
myBook.setPrice(64.95);
// print the information about the book
System.out.println(myBook.toString());
System.out.println("The price of the book is: " +
myBook.getPrice () );
System.out.println("The subject is: " + myBook.getSubject ()
);
} // end main()
} // end class BookProject
The two files – Book.java and BookProject.java are both part of
the same Java project, and are in the
54. same src folder within the project. The Book class in the
Book.java file is visible to main() method in the
Main class in BookProject.java. because the files are the same
folder (and in the same project).
This is the preferred way to organize object declarations in Java
– each class is in its own file. This
supports the notion of de-coupling objects so they more easily
can be used independently of one
another.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 8
Lab 9A starting on the next page shows you how to create this
example in IntelliJ IDEA. It demonstrates
creating a class in its own file in an IntelliJ project and then
accessing that class from the main() method
in the executable class.
Independent Classes in a Single Java File
Multiple classes can be defined in a single Java file, either one
after
another in sequence, or using nested classes. This works, but
remember, only one class in each file can be a public class. For
this
55. reason, placing each class in its own file is recommended
instead of
multiple classes in the same file, unless we wish to "hide" the
non-
public classes.
If we do want multiple independent class declarations in a
single file,
they should be placed in the file one after another as shown
below.
Typically, if one of the classes is an executable class with a
main()
method, that class is at the top of the file.
Only a public class can be accessed by other software. So, if we
have
multiple classes, then the private classes could be classes that
define
objects for use in the public class that we do not wish other
software to be able to see or use. In
essence, classes other thasn the one public class in the file are
encapsulated within the file.
However, the use of nested classes is preferred over having
multiple classes independently defined in
the same file.
56. Nested Classes in a Single Java File
One class can be defined within another class. The inside class
is known
as a nested class. If it is not a static class, it is called an inner
class. If it a
static class, it is known as a static nested class. The use of static
inner
classes is beyond what we wish to cover in this chapter, so we
will just
briefly look at inner classes.
An inner class in only visible to the class in which it is
contained. An
object defined by an inner class will only be useable within the
containing class. If we wish to have an encapsulated object that
is
"hidden" from other software, it can be declared in an inner
class. If we
want the object to be useable elsewhere, then it should be
defined in its
own class file.
No special notation is needed for an inner class – the class
declaration simple needs to be within
57. another class. The Java project InnerClassDemo, included with
this project, is an example of the use of
an inner class.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 9
Lab 9A – Creating Multiple Independent Class Files in IntelliJ
IDEA
This lab demonstrates how to create multiple, independent class
files in IntelliJ IDEA within the same
programming project. Our project will be named
"BookProject", the executable class will have intelliJ's
default name for the executable class "Main", and this will
contain the project's main() method. All of
this is similar to what you have done before. What's new is that
we will also create a second class file
within the project, Book.java, which will contain the class
declaration used to create instances of the
book class within the main() method in the Main.java file.
Objects must be defined in a class before they can be used. The
development of an IntelliJ IDEA project
with multiple classes occurs in three phases:
phase 1 – start the project
58. phase 2- create the classes that will define the objects to be
used in the project. Each class will be in its
ow file.
phase 3- create the code in the executable class that will use the
objects in the project.
The rest of this lab will walk you through this process, step by
step.
STEP 1.
Start IntelliJ IDEA, then from the opening menu, select
Create New Project.
A New Project window will open.
STEP 2.
On the new Project screen that appears,
make sure Java is selected to start a new
Java project, then click the [Next] button.
The New Project window will change to
show ask you about a project template.
59. CSCI 111 Chapter 9 – Classes and Objects in Java pg. 10
STEP 3.
Click the checkbox to create project from
template, select the Command Line App template,
then click the [Next] button to continue.
The New Project window will change to ask you about
the name and location of your project files.
STEP 4.
The project name will be BookProject.
Fill in the Project name field with "BookProject", make
sure the Base package is also "BookProject", and
make sure the Project location is set to be what you
60. want it to be, as you would with any IntelliJ project.
It is usually best to make the package name and the
name of the project to be the same.
This example shows the desktop as the location.
Choosing a location fpr the project is up to you. You
may want to work on the desktop then copy the
project folder to a nother location for long term
storage.
When the data in the three fields is what you want it
to be, then click the [Finish] button to create your
project.
Now you should be able to see the main() method in the Main
class of your Java project.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 11
STEP 5.
Before going any further, add proper documentation to your
Main.java file, similar to the following:
61. /* Main.java
* This file contains the executable class for a project
* demonstrating the use of a Book object
* last edited November 20, 2019 by C. Herbert
* The file declaring the Book class must be visible to this Main
class.
*/
Also, label the closing braces for the main() method and for the
Main class:
} // end main()
} // end class Main
STEP 6.
Now that we have a project, we can create the Book class that
will be used to instantiate Book objects
within the project. We need the Book class to be defined before
we can create a Book object in the
main() method.
From the IntelliJ IDEA File menu, select New, then select Java
Class from the pop-up sub-menu that
62. appears.
A New Java Class file menu will appear, as shown below:
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 12
STEP 7.
Type "Book" in the space for the Name, and then double-click
Class in the menu to create a blank Java
class file named Book.java.
The Book.java file should appear in your IntelliJ editing
window as shown here:
Notice that a few things have happened. There are now two
tabs in the editing window –one for
Book.java, and one for Main.java. You can click on either tab
to see or to work with either file.
The BookProject folder within the src folder now has two
source code files in it – Book and Main.
The Book.java tab should be selected in the editing window, as
shown above, so that you can see the
Book.java class file. It contains the package declaration
63. indicating that this new file is part of the
BookProject package, and the Book class file, but the class has
no code in it yet.
STEP 8.
Before going any further, let's add proper documentation to this
class file, similar to the following:
/* Book.java
* This file contains the declaration for the Book class of
objects,
* as used in our textbook
* last edited November 20, 2019 by C. Herbert
* The file declaring the Book class must be visible to this Main
class.
*/
Also, label the closing brace for the class:
} // end class Book
When you are finished, you can save your work by Building the
project. It should build quickly, ssince
there is very little code in the project so far.
STEP 9.
64. Now we need to create the code to define the Book object. We
will need to add properties, constructor
methods, accessor methods, etc., to the Book class. The code
that we will use for this is shown starting
back on page 3 of this chapter. and in the file Book.java
included with the files for this chapter in Canvas.
You can cut and paste the code into your Book.Java class or
retype the code yourself. Copy and paste
the code defining the properties and methods between the
opening brace following the class header
and the and closing brace that we just labeled as the end of the
class.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 13
When you are finished, you code should match the code in the
file Book.java. Correct any errors that
may have occurred when you copied the code, then build the
project again to save your work.
STEP 10.
Now that we have a Book class, we can use it in the main()
method in the Main class to create a Book
object.
We will keep this simple. We wish to create a book with the
65. following information:
• ISBN: 978-02-62031417
• title: Introduction to Algorithms
• subject: Computer Science
• price: $64.95
We will instantiate a Book object with the initializing
constructor that uses ISBN and title as parameters.
We will use the variable myBook to refer to this book. Then, we
will use mutator methods to add values
for the subject and price properties of the object.
Let's turn the description from that last paragraph into
comments in Java.
// create an instance of the book class with an ISBN and title
// add a subject
// add a price
Click the tab to access the Main class in the IntelliJ Idea editor
and add these three comments to your
main() method. Your Main class should something look like
this:
66. CSCI 111 Chapter 9 – Classes and Objects in Java pg. 14
STEP 11.
Now we can add the Java instructions to do what each comment
says to do, as follows:
// create an instance of the book class with an ISBN and title
Book myBook = new Book("978-02-62031417","Introduction To
Algorithms");
// add a subject
myBook.setSubject("Computer Science");
// add a price
myBook.setPrice(64.95);
STEP 12.
Our last step is to add code to print the information for
myBook. We will use the accessor methods
toString(), getSubject() and getPrice() to do this. Add the
following code to your main() method:
// print the information about the book
67. System.out.println(myBook.toString());
System.out.println("The price of the book is: " +
myBook.getPrice () );
System.out.println("The subject is: " + myBook.getSubject () );
The main() method in your Java project should now look like
this:
That's it, we are done! You now have a
Book class and software that
instantiates ad uses a Book object.
Build and run your software. Your
output should be similar to that shown.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 15
9.3 Use of the Java Keyword this
The Java keyword this may be used in a method to specify the
properties of the instance of the for
which the method has been invoked. It is most often used in a
method where a method variable or a
68. method parameter has the same name as a property of the
object.
Consider the following example from the Book class that
appeared near the beginning of this chapter.
The book class has a constructor with two parameters, number
and name as follows:
public Book(String number, String name)
{
isbn = number;
title = name;
} // end Book(String number, String name)
However, what happens if the two parameters have the same
name as the object's properties, like this:
public Book(String isbn, String title)
{
isbn = isbn; // note that these two lines are incorrect
title = title; // no errors, but they don’t work as expected
} // end Book(String isbn, String title)
How does the computer know whether isbn refers to parameter
69. or to the objects isbn property? The
statement isbn = isbn; can cause confusion for a compiler and
for a person reading the method. The
compiler will assume that isbn is the name of the variable or
parameter, and not the name of an object’s
property. It makes sense to the compiler and no error is
generated, but it just doesn’t work as we
wanted it to work. It sets the variable isbn equal to itself and
does not change the object's isbn property.
The keyword this is designed to solve the problem. this.isbn
will refer to the property isbn for the
instance of the object that was used to invoke the method.
Here is the method with the keyword this:
public Book(String isbn, String title)
{
this.isbn = isbn; // note: this works as expected
this.title = title;
} // end Book(String isbn, String title)
The keyword this can always be used to indicate an object's
property, even if it doesn't have the same
name as a method parameter or method variable. Even though it
70. always appropriate when referring to
properties of an object, we only need to use it if a property and
a variable or Parmenter have the same
name. Some programs always use this, while others only use
this when necessary.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 16
9.4 Example – Array of Objects: Monopoly Board Squares
As we saw in Chapter 8, each element in an array of objects is a
reference variable holding the address
of an object. The example below demonstrates the creation of
an array of objects.
In this example we will create an array of
squares for a Monopoly board, then place the
squares in an array of objects. First, we must
define a class for the squares, and then we can
place them in an array.
We will start with a description of the squares
and a UML diagram of the class.
There are 40 squares on a Monopoly board, as
71. shown here.
There are different types of squares:
• Property. These squares can be bought
and sold. A player who lands on a
property must pay rent. Each property
belongs to a color group. A Monopoly
property has the attributes name, price,
rent, color and owner.
• Railroad. Railroads can also be bought and sold, but the rent
for a player who lands on a
railroad square depends on the number of railroads in
possession of the owner. These squares
only have a name and an owner.
• Utility. Utilities can be bought and sold. The rent depends on
the roll of the dice when a player
lands on the square. Utilities, like railroads, only have the
properties name and owner.
• Community squares. There are several other squares that can
be grouped together as
community squares that do not have an individual owner and
cannot be bought or sold. The
72. action to be performed when a player lands on a community
square depends in the specific
square. They each only have a name, but no owner, price, or
fixed rent. The community squares
include:
o two card squares (Chance and Community Chest) with cards
to determine what happens
when a player lands on one of these squares.
o two tax squares (Income Tax and Luxury Tax) that each have
a formula for determining the
tax a player pays to the bank when landing on one of these
squares.
o two free squares – Just Visiting and Free Parking on which
nothing happens. The game's
jail is on the Just Visiting square.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 17
o The Go square, on which the game starts. Players are paid
$200 each time they go around
the board and pass the Go square.
o a Go to Jail square, which sends a player to jail.
73. We are going to create a simplified version of the game with an
array of board square objects with
simplified properties. This is typical in software development.
A complex piece of software might be
developed in stages, with a simplified design used for early
stages and complexity added during later
stages of development.
For our simplified version of the game, the rent for railroads
will be fixed at $25, the rent for utilities will be
fixed at $15, and the community squares will be inactive, in
effect being all free parking. Each square will
have five properties: name, type, rent, price and color.
Our simplified game will have four types of squares: property,
railroad, utility, and community. We will not
keep track of who owns which square in this version of the
game.
Information about each square for our simplified game is
summarized in the following table.
Name type Rent price color
Go community 0 0 null
Mediterranean Ave. property 2 60 Dark Purple
Community Chest community 0 0 null
74. Baltic Ave. property 4 60 Dark Purple
Income Tax community 200 0 null
Reading Railroad railroad 25 200 null
Oriental Ave property 6 100 Light Blue
Chance community 0 0 null
Vermont Ave. property 6 100 Light Blue
Connecticut Ave. property 8 120 Light Blue
Jail/Just Visiting community 0 0 null
St. Charles Place property 10 140 Light Purple
Electric Company utility 10 150 null
States Ave. property 10 140 Light Purple
Virginia Ave. property 12 160 Light Purple
Pennsylvania Railroad railroad 25 200 null
St. James Place property 14 180 Orange
Community Chest community 0 0 null
Tennessee Ave. property 14 180 Orange
New York Ave. property 16 200 Orange
Free Parking community 0 0 null
75. Kentucky Ave. property 18 220 Red
Chance community 0 0 null
Indiana Ave. property 18 220 Red
Illinois Ave. property 20 240 Red
B & O Railroad railroad 25 200 null
Atlantic Ave. property 22 260 Yellow
Ventnor Ave. property 22 260 Yellow
Water Works community 10 150 null
Marvin Gardens property 24 280 Yellow
Go To Jail community 0 0 null
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 18
Pacific Ave. property 26 300 Green
No. Carolina Ave. property 26 300 Green
Community Chest community 0 0 null
Pennsylvania Ave. property 28 320 Green
Short Line Railroad railroad 25 200 null
Chance community 0 0 null
76. Park Place property 25 350 Dark Blue
Luxury Tax community 100 0 null
Boardwalk property 50 400 Dark Blue
We wish to create a BoardSquare class of objects, based on the
information in the table above. We can
see that there we need are five data properties for each square:
• name – the name of the square
• type – the type of the square. There are six types: property,
railroad, utility, plain, tax, and toJail
• price – the cost to buy the square. A price of zero means the
square is not for sale.
• rent – the rent that a player who lands on the square must pay.
• color – the color of the square. only property squares have
color, the rest are null.
We need public methods to get each property, but not to set
each property, since users will not be able
to change the properties of each BoardSquare. The
BoardSquare's values will be set by a constructor. In
this case, the set of methods will be simple – two constructors
(one null constructor and one initializing
constructor) and the accessor method for each BoardSquare’s
77. property, plus a toString() method.
We will use Strings for most properties. The price and the rent
will be integers. Here is an annotated
UML diagram for the BoardSquare class:
BoardSquare (board squares for a Monopoly game)
- name: String
- type: String
- price: int
- rent: int
- color: String
name of the square
property, railroad, utility, or community
color group; many are null
+ BoardSquare(): void
+ BoardSquare(String, String, int, int, String): void
+ getName(): String
+ getType(): String
+ getPrice() int
+ getRent() int
+ getColor:(() String
+ toString:() String
(name, type, price, rent and color)
78. returns data about the square as a String
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 19
Here is the code for the corresponding class of BoardSquare
objects:
/* BoardSquare.java
* CSCI 111 Fall 2019
* last edited November 22, 2019 by C. Herbert
*
* This file defines the BoardSquare class
* for BoardSquare objects in a simplified version of a
Monopoly game.
* The BoardSquare class is required for the project to work
properly.
*
* This is for teaching purposes only.
* Monopoly and the names and images used in Monopoly are
* registered trademarks of Parker Brothers, Hasbro, and others.
79. */
package monopoly;
public class BoardSquare {
private String name; // the name of the square
private String type; // property, railroad, utility, or
community
private int price; // cost to buy the square; zero means not
for sale
private int rent; // rent paid by a player who lands on the
square
private String color; // many are null; this is not the Java
Color class
// constructors
public BoardSquare() {
name = "";
type = "";
price = 0;
rent = 0;
color = "";
80. } // end Square()
public BoardSquare(String name, String type, int price, int
rent, String color) {
this.name = name;
this.type = type;
this.price = price;
this.rent = rent;
this.color = color;
} // end BoardSquare()
// accessors for each property
public String getName() {
return name;
} //end getName()
public String getType() {
return type;
} //end getType()
81. public int getPrice() {
return price;
} //end getPrice()
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 20
public int getRent() {
return rent;
} //end getRent()
public String getColor() {
return color;
} //end getColor()
// a method to return the BoardSquare's data as a String
public String toString() {
82. String info;
info = (name + ", " + type + ", " + price + ", " + rent + ", "
+ color);
return info;
} //end toString()
} // end class BoardSquare
//***************************************************
************************
The executable class in the Monopoly project is named
Monopoly and is in the file Monopoly.java. It
uses the BoardSquare class to create an array of BoardSquares.
The main() method:
• creates an array of 40 BoardSquares and assigns the variable
square to refer to the array. The
properties of the BoardSquares are null at the time it is created.
• calls the method loadArray(), which initializes the properties
of the 40 BoardSquares from data
in a file named "squares.txt"
• calls the method printArray(), to test the software by printing
the properties of each element in
83. the square[] array.
/* Monopoly.java
* CSCI 111 Fall 2019
* last edited November 22, 2019 by C. Herbert
*
* This file contains the executable class Monopoly
* for a simplified version of a Monopoly game.
* It requires access to the BoardSquare class to work properly.
*
* The software creates an array for 40 BoardSquares and loads
data
* into the array from a simple text data file
*
*It also has code to test the program by printing the data from
the array
*
* This is for teaching purposes only.
* Monopoly and the names and images used in Monopoly are
* registered trademarks of Parker Brothers, Hasbro, and others.
84. */
package monopoly;
import java.util.*;
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 21
public class Monopoly {
public static void main(String[] args) throws Exception {
// create an array for the 40 squares on a Monopoly board
BoardSquare[] square = new BoardSquare[40]; // array of
40 monopoly squares
// call the method to load the array
loadArray(square);
// test the code by printing the data for each square
printArray(square);
85. } // end main()
//***************************************************
********************
// method to load the BoardSquare array from a data file
public static void loadArray(BoardSquare[] sq) throws
Exception {
// declare temporary variables to hold BoardSquare
properties read from a file
// each variable corresponds by name to a property of a
BoardSquare object
String inName;
String inType;
int inPrice;
int inRent;
String inColor;
// Create a File class object linked to the name of the file
to be read
java.io.File squareFile = new java.io.File("squares.txt");
86. // Create a Scanner named infile to read the input stream
from the file
Scanner infile = new Scanner(squareFile);
/* This loop reads data into the array of BoardSquares.
* Each item of data is a separate line in the file.
* There are 40 sets of data for the 40 squares.
*/
for (int i = 0; i < 40; i++) {
// read data from the file into temporary variables
// read Strings directly; parse integers
inName = infile.nextLine();
inType = infile.nextLine();
inPrice = Integer.parseInt(infile.nextLine());
inRent = Integer.parseInt(infile.nextLine());
inColor = infile.nextLine();
// initialze each array element with the BoardSquare
initializing constructor
sq[i] = new BoardSquare(inName, inType, inPrice,
inRent, inColor);
87. } // end for
infile.close();
} // endLoadArray
//***************************************************
********************
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 22
// test method to print data from the array of BoarsSquares
public static void printArray(BoardSquare[] sq) throws
Exception {
// print header above each row
System.out.println("Data from the array of Monopoly
board squares.n");
System.out.printf("%-22s%-12s%6s%6s%14s%n", "name",
"type", "price", "rent", "color");
88. System.out.println("************************************
****************************");
// print data in formatted columns, one square per row
for (int i = 0; i < 40; i++) {
System.out.printf("%-22s", sq[i].getName());
System.out.printf("%-12s", sq[i].getType());
System.out.printf("%6d", sq[i].getPrice());
System.out.printf("%6d", sq[i].getRent());
System.out.printf("%14s%n", sq[i].getColor());
} // end for
} // end printArray
//***************************************************
********************
} // end class BoardSquare
//***************************************************
************************
Each element in the array square will now be a reference
89. variable, holding the memory address where
the corresponding BoardSquare object is actually stored in
memory.
square[0] square [1] square [2] square [3] . . .
4000H 4128H 4224H 4380H . . .
square[0]
name: Go
type: community
rent: 0
price: 0
color: null
square[1]
90. name: Mediterranean Ave.
type: property
rent: 2
price: 60
color: Dark Purple
square[2]
name: Community Chest
type: community
rent: 0
price: 0
color: null
square[3]
name: Baltic Ave.
type: property
rent: 4
price: 60
color: Dark Purple
91. CSCI 111 Chapter 9 – Classes and Objects in Java pg. 23
9.5 Abstract Methods, Abstract Classes, and Java Interfaces
An abstract method in Java is a method that only has a method
header – including its return type,
name, and parameter list – but no method body. It’s really not
a method, just information about the
method. Abstract methods are used to create Java interfaces
and Abstract classes, which we learn more
about in just a moment.
The header for an abstract method starts with the keyword
abstract and ends with a semicolon, such as
in the following examples:
abstract double getArea();
abstract void draw();
abstract void resize();
Each of these three might be used in a program that draws
shapes on the screen.
A concrete method is a method that is not abstract – in other
words, the normal methods that we have
been using so far.
Obviously, abstract methods can’t do anything, but can they
form the basis for extensions of Java
92. Abstract classes and implementations of Java interfaces that can
do things.
Abstract Classes
An abstract class is a class that cannot be instantiated – in other
words, no objects of the class can be
created. An abstract class serves as the basis for subclasses that
can be instantiated.
An abstract class may contain one or more abstract methods.
Any class that contains at least one
abstract method must be declared as an abstract class. The
following example shows how and why
abstract classes are used.
Example of an Abstract Class – the Shape Class
Imagine that we wish to have a graphics program that can draw
a variety of shapes on the screen, and
can give us information about the shapes it draws – color,
perimeter, area, location, and so on. The
shapes will be in different classes that have different properties.
For example, a circle will have a radius, whereas a square will
have a side, and a rectangle will have a
long side and a short side. All of the shapes will have an area, a
perimeter, a color, and a location.
93. The methods to draw the shapes on the screen will work
differently for different shapes. The software
will use the location of the center of a circle and its radius to
draw a circle, while it will use the location
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 24
of the top left corner of a square and the length of its side to
draw a square. The classes for rectangles,
ellipses, regular hexagons, triangles, parallelograms, and so on,
will all use different information to draw
the shapes, but they will all have draw methods; The same is
true for area methods and perimeter
methods; each class will have them , but they will not all work
the same way.
This is an obvious case where inheritance can be used. We can
set up a parent class, named Shape, with
subclasses Circle, Square, Rectangle, and so on. All of the
objects in the graphics system will be objects
of one of the subclasses of Shape – they will all be circles,
squares, rectangles, and so on. No objects of
the parent class Shape will be created. A few properties – such
as location, color, area and perimeter –
will be common to all shapes but other properties and most
94. methods will be different for each subclass.
This is the perfect case for an abstract class. We will declare
Shape to be an abstract class, which means
there will be no Shape objects. The objects will be in
subclasses of Shape . We will put the common
properties in the Shape class to be inherited by the subclasses.
We will also give the shape class abstract methods for draw,
area, and perimeter, which will tell
programmers that the subclasses must implement these methods.
Concrete classes that are subclasses
of abstract classes must implement the abstract classes inherited
from the abstract parent class.
Here is what the abstract parent class Shape will look like:
abstract class Shape {
// declare properties
Point location; // an object of type Point has an x and y
coordinate
Color color; // using Java’s built in Color class
double area;
double perimeter;
95. // declare concrete methods -– accessors for location and color
Point getLocation() {
return location;
}
Color getColor() {
return color;
}
// declare concrete methods – mutators for location and color
void setLocation(Point location) {
this.location = location;
}
void setColor(Color color) {
this.color = color;
}
// declare abstract methods
abstract void draw();
96. abstract double calculateArea();
abstract double calculatePerimeter();
}// end abstract class Shape
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 25
The abstract class Shape can now be used as the basis for
subclasses. The subclasses will inherit the four
properties – location, color, area, and perimeter – and the
concrete methods, and they must implement
the abstract methods draw(), calculateArea(), and
calculatePerimeter(). The code for the Circle class,
minus some of the details, is shown below.
class Circle extends Shape {
// declare Circle specific properties
private double radius;
private Point center; // center and location will be the same
point.
// constructors
public Circle() {
97. radius = 0;
area = 0;
perimeter = 0;
} // end Cirlce()
public Circle(Point location, double radius, Color color) {
this.location =location;
this.radius = radius;
this.color = color;
// re-calculate area and perimeter whenever radius changes
area = calculateArea();
perimeter = calculatePerimeter();
} // end Circle( --- )
// add additional accessors
public double getRadius() {
return radius;
} // end getRadius()
98. public double getCenter() {
return center;
} // end getCenter()
public void setRadius(double radius) {
this.radius = radius;
// re-calculate area and perimeter whenever radius changes
area = calculateArea();
perimeter = calculatePerimeter();
} // end setRadius
// add additional mutators
// implement classes that were abstract in the super class
(parent class)
public void draw(){
// put the code here to draw a circle
} // end draw()
99. CSCI 111 Chapter 9 – Classes and Objects in Java pg. 26
private double calculateArea() {
// area = π * r^2
return Math.PI * radius * radius;
} // end calculateArea()
private double calculatePerimeter() {
// area = 2 * π * r
return Math.PI * 2.0 * radius;
} // calculatePerimeter()
// add additional methods for the Circle class here
} // end class circle
To summarize the use of Abstract classes:
• Abstract methods are methods that have no body, just the
method header.
• An abstract class is a class that has at least one abstract
method.
• An Abstract class cannot be instantiated – no objects of that
100. class can be created.
• Abstract classes are the basis for concrete classes that can be
instantiated.
• An Abstract class may contain properties and concrete
methods that subclasses have in
common, and abstract methods for other methods that the
subclasses must have, but which will
work differently in different subclasses.
UML Diagrams for Inheritance and Abstract Classes
We use arrows to denote subclass relationships (inheritance) In
UML diagrams, pointing from the
subclasses to the superclass. The arrowheads are supposed to
be open arrowheads , but often
solid arrowheads are used because they are much easier to draw.
The simplified UML diagram
below shows this. Book and and EMail both are subclasses of
Document.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 27
Technically, the UML standard only calls for abstract class
names and abstract method names to be
italicized, but often people put the word “abstract” with the
101. names to make it more obvious that they
are abstract.
Java Interfaces
Abstract methods can also be used in Java Interfaces. Java
Interfaces are very similar to abstract classes,
but they have two differences:
1. Interfaces can only have abstract methods, not concrete
methods. Interfaces can have
constants, but not properties or concrete methods. (An abstract
class can have concrete
methods as well as abstract methods.)
2. Interfaces are implemented not inherited; they are not used as
super classes. A concrete class
can implement more than one interface.
Interfaces have no constructors, and are not classes that can be
instantiated. They provide a standard
set of method calls for other classes.
A class implements an Interface by using the phrase
”implements [interface name]” immediately after
the name of the class in the class declaration.
Java interfaces are used to provide a common set of method
calls for use within many classes. In
102. essence, they form a contract that says “This class will include
the methods listed in the interface, with
the same method names, parameters and return types.”
Effectively, an interface in Java is a list of
abstract methods that will be implemented in any class that
implements the interface.
Imagine that we have several major electronic companies
making burglar alarms, cable television boxes,
microwave ovens, and so on, all of which use an electronic
clock with a display and a programmable
clock chip made by one manufacturer. The manufacturer could
publish a Java interface showing how to
invoke the methods to program the chip. The various other
manufacturers could include the interface
in the Java code for their devices, so that programmers creating
software for the various systems could
all use the same method names, parameters, etc, for any clock
software, making all of the system more
compatible with one another.
The code below shows a clock interface.
interface Clock {
void setTime(int hours, int minutes, int second);
103. void setHours(int hours);
void setTimeZone(int zone);
void setMinutes(int minutes);
void setSeconds(int seconds);
int getHours();
int getMinutes();
int getSeconds();
int getTimeZone();
} // end interface Clock
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 28
By publishing the interface, the clock chip manufacturer is
telling others : “these methods are
guaranteed to work in our system.” The Java software in the
clock would implement this interface, as
would any software in any compatible system that also declares
that it implements the interface.
To implement an interface, the class header should include the
declaration “implements [name of
104. interface]” immediately after the class name. For example a
class named Timer that implements the
Clock interface might have a class declaration that starts like
this:
Public class Timer implements Clock
{
// body of the Timer class goes here – properties and methods
as usual
}
This tells the world that the Timer class has code implementing
all of the abstract methods in the Clock
interface. Someone who knows the Clock interface would then
know how to invoke and use the similar
methods in Timer. In a similar manner, someone who knows
the Clock interface would also know how
to use the related methods in any system that implements Clock
– household appliances, entertainment
systems, communications equipment, and so on.
In some systems, the interface that specifies the behavior is
called the supplier, and the class that
implements the behavior is called the client.
In the modern world, with so many systems interacting with one
105. another all around the Earth via the
Web, through mobile devices, via telephone and radio systems,
and so on, Java interfaces go a long way
toward ensuring some compatibility among software systems.
Interfaces are one of the reasons the
Java language is used so widely in so many large complex
computer systems.
To summarize the use of Java interfaces:
• An interface is a collection of methods, similar to those found
in a class, but all of the interface’s
methods are abstract methods.
• An interface could also include properties and constants, but
often only has abstract methods.
• A class that implements an interface will have methods that
match the abstract methods in the
interface, with the same method names and matching
parameters.
• An interface is like a contract, with any class that implements
the interface guaranteeing that
the methods listed in the interface will work in the class.
• classes can implement more than one interface.
• interface implementation is independent of inheritance.
Interfaces cannot be inherited; a class
106. cannot extend an interface.
• a programmer declares a class will implement an interface by
including “implements [interface
name]” immediately after the class name, such as in “public
class Timer implements Clock { … ”.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 29
Interfaces in UML diagrams
The implementation of interfaces in UML diagrams is shown by
using an arrow with a dotted line
pointing from a class to any Interfaces it implements. In the
following simplified example, both the
Professor class and the Student class implement the Person
interface:
Java’s Comparable Interface
One commonly used Java interface is the Comparable interface,
whose only method is the CompareTo()
method. The CompareTo() method compares two objects in a
class and returns an integer.
The integer returned by a.compareTo(b) will be:
107. • a negative number if a comes before b;
• a zero if a equals b;
• a positive number if a comes after b.
An example of how this is used is the The String class
CompareTo() method, which uses the lexicographic
order (alphabetic order) of the Unicode characters in the String
to compare them. It is most often used
in an If statement, such as in this code from the BubbleSort
demo example in Chapter 6:
if ( a[i+1].compareTo(a[i]) < 0 ) // if the two items are out
of order
{
// swap the two items and set swapped to true
c = a[i];
a[i] = a[i+1];
a[i+1] = c;
swapped = true;
} // end if
The pattern of use for the compareTo() methods in if statement
108. basically is:
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 30
• if (a.compareTo(b) < 0) // then a comes before b.
• if (a.compareTo(b) == 0) // then a equals b.
• if (a.compareTo(b) > 0) // then b comes before a.
But this only works if we implement the compareTo() method in
a way that tells the computer how to
compare two items in a newly defined class, as the String class
does. How will objects in a new class be
compared?
To implement the comparable interface in a new class, we need
to include code for the compareTo()
method in a class declaration telling the computer how to
compare two items in the new class. The
following example shows how to do this with the Book class
from the beginning of the chapter.
Example – implementing Java’s Comparable Interface
Here is part of the class declaration for the Book class:
public class Book
{
109. // declare properties
private String isbn;
private String title;
private String subject;
private double price;
// constructor methods ******************************
public Book()
{
} // end Book()
the rest of the class declaration follows this . . .
For the compareTo() method to work, we need to decide what
to use as the basis for the order of our
books. We can use any property that already has a predefined
order, such as the ISBN or the title, which
are Strings. If the new class has a property that is a key field,
then that should be used as the basis for
the compareTo() method. A key field is a field that has a
unique value for each instance of an object.
110. Your Jnumber at CCP is an example of a key field – no two
students can have the same Jnumber. Social
security numbers, bank account numbers, and Vehicle
Identification Numbers (VIN) are all examples of
key fields.
isbn is a key field. It can be used to compare two objects. The
following code shows how to implement
the compareTo() method in the book class using the String
property isbn:
/* compareTo() method using ISBN as the basis for ordering
Book objects
* a.compareTo(b) compares Book a to Book b
public int compareTo(Book b)
{
int x;
x = this.isbn.compareTo(b.isbn);
return x;
} // end Book()
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 31
111. In the code shown here, this.isbn is the isbn property for the
Book object invoking the method. In code
outside of the class, Book object a can be compared to Book
object b this way - a.compareTo(b);
The isbn property is a String, so one isbn is compared to
another in the method by using the String class
compareTo() method. this.isbn.compareTo(b) invokes the
String compareTo() method for this.isbn. The
Book compareTo() method then returns the result of that String
comparison. The result is that Book
class objects will now be compared by their isbn properties
whenever a program uses compareTo() with
Book class objects.
The Book class header can now include the “implements
comparable” phrase:
public class Book implements Comparable
{
// declare properties
private String isbn;
private String title;
private String subject;
private double price;
112. // constructor methods ******************************
public Book()
{
} // end Book()
. . . other methods would follow here, including
public int compareTo(Book b)
{
int x;
x = this.isbn.compareTo(b.isbn);
return x;
} // end Book()
the rest of the class declaration follows this . . .
We can include the Book compareTo() method in the Book class
declaration without implementing
Java’s comparable interface, so why should we bother to do so?
The answer is to let programmers know
113. that our class of objects can be compared and ordered using this
standard method. By putting a
compareTo() method in the Book class declaration and
including the “implements comparable” phrase
with the Book class header, we are telling other programmers
that Book objects can be compared to
one another, so they can be sorted, etc.
Think of it like a badge worn by a soldier. A soldier who is a
properly trained combat parachutist wears a
badge with combat jump wings on his uniform, indicating he is
a trained parachute jumper. In a similar
manner, the “implements comparable” phrase indicates that a
class includes a proper compareTo()
method.
Please note that the comparable interface is included in the
standard Java.lang package, so it can be
used without any import statement. Other Java interfaces, such
as some of those used in GUI
programming, may need import statements to work in you code.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 32
9.6 Copying Objects
114. We have seen that a reference variable is used to refer to the
location where the details of an object are
actually stored. For example, imagine that we have two objects
from the Book class, bookA and bookB.
Each variable will point to the memory location where the data
for its object is stored.
In chapter 8 we saw that setting BookB equal to BookA with
the statement BookB = BookA; changes
the value of the reference variable so that they both point to
BookA. The old data from BookB is lost.
bookA
bookB
115. But what if we want BookB to be a copy of BookA? The copy
shown above, where the reference is
copied so that two variables refer to the same object in memory
is known as a shallow copy. Copying all
of the properties of one object to another object of the same
type is known as a deep copy. A deep copy
bookA
bookB
bookA
isbn: 978-1400033416
title: Beloved
subject: fiction
price: 23
bookB
isbn: 978-0316769174
title: The Catcher in the Rye
subject: fiction
116. price: 14
bookB
isbn: 978-0316769174
title: The Catcher in the Rye
subject: fiction
price: 14
bookA
isbn: 978-1400033416
title: Beloved
subject: fiction
price: 23
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 33
copies the state of one object to another. The diagram below
shows what a deep copy would look like.
We need to write a method to perform a deep copy.
117. Here is a method to perform a deep copy for the Book class:
public void copy(Book source)
{
this.isbn = source.isbn;
this,title = source.title;
this.subject = source.subject;
this.price = source.price;
)
The code to copy BookA to BookB would then look like this:
BookB.copy(BookA);
All of the properties of BookA are copied to BookB.
A Copy Constructor in Java
Once we have a copy() method in our class, we can easily set up
a copy constructor. A copy constructor
is a constructor that creates a new instance of an object and
copies the state of an existing object into
the new object. It creates a new copy of an object initialized
118. with all of the properties of the object it is
copying. The code for a copy constructor in the Book class
would like this:
Book( Book source)
{
this.copy(BookA);
)
Of course, this only works when we have already have a copy()
method. A copy constructor is used like
this:
Book bookD = new Book(bookA);
It is very useful to include a copy method and a copy
constructor in declarations for new classes.
bookA
bookB
bookB
isbn: 978-1400033416
title: Beloved
subject: fiction
119. price: 23
bookA
isbn: 978-1400033416
title: Beloved
subject: fiction
price: 23
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 34
Chapter Review
Section 1 of this chapter described class declarations for a new
class of objects in Java. Key terms
included: class declaration and default constructor. (Note: Most
of the new key terms for this topic
were introduced in the previous chapter.)
Section 2 discussed two ways to organize class declarations in
Java code: multiple classes in a single
*.java file, and inner classes. Key terms included inner class
and nested classes.
Section 3 described appropriate use of the Java Keyword this.
Section 4 described how arrays of objects work in Java, using
120. reference variables.
Section 5 discussed the Java abstract methods and their use in
Abstract Classes and Java interfaces,
including the use of Java’s Comparable interface. Key terms
included: abstract method, concrete
method, abstract class, interface, and key field.
Chapter Questions
1. By what other name is a Java class declaration also known?
What is a default constructor? What
happens if a Java Class declaration does not have a constructor?
2. In a .java file, when should a class be public? What class is
always public in a .java file? How many
classes in a .java file can be public?
3. How are inner classes declared in Java? When is an inner
class a good idea, and when is it a bad idea?
4. What does the keyword this refer to in a Java method?
When should it be used?
5. What is a static property? How are static properties invoked?
6. What is actually stored in an array of objects in Java?
7. How is an abstract method declared in Java? How is it
different from a concrete method?
8. How is an object of an abstract class instantiated in Java?
121. What are abstract classes used for? What
classes must be declared as an abstract class?
9. What do we know about all of the methods in a Java
interface? What does implementation of an
interface by a class guarantee for a programmer using the class?
How many interfaces can a class
implement?
10. How is inheritance indicated on a UML diagram? How is
implementation of an interface indicated?
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 35
Chapter Exercise
Creating A Player Class for a Monopoly Game
The Java project Monopoly in the files for this chapter, has two
classes described earlier in the chapter –
the executable class Monopoly.java and BoardSquare.java
which defines a BoardSquare object.
Your task is to create a new class for a Player object in a
monopoly game, and to revise the existing
Monopoly project to test the player class by moving the player.
We are not implementing a complete
122. Monopoly game, but just creating a Player class and testing how
it works within the project.
You should:
1. Design and create the class declaration for the Player class
according to the annotated UML
diagram below, and add it to the IntelliJ Monopoly project in a
new Java class file.
2. Modify the executable Monopoly class to test the player, as
follows:
a. you should instantiate a player object. ( … such as, Player p1
= new Player();
p1 is just an example. You can decide what to name the
variable.)
b. initialize the player’s location to be square 0, the Go square.
the player’s location will be
the square that the player’s token is currently on.
c. initialize the players name and token with values you choose,
such as "Joe" and "the
race car". Initialize the players balance to be 1500.
d. print the initial data for the Player, such as
the race car is on GO. Joe's Balance is $1,500.
e. create a loop to move the player 10 times. The loop should:
123. i. pick two random numbers between 1 and 6 and add them
together to simulate
the rolling of a real pair of dice.
ii. move the player (change location) to the new square by
adding the player's
location to the value rolled by the dice. (If the value is greater
than 39, then
subtract 40. This accounts for starting again at the start of the
board.)
The code could look like this:
newLocation = p1.getLocation() + roll;
if (newLocation > 39)
newLocation = newLocation - 40;
p1.setLocation(newLocation);
iii. subtract the square's rent from the player's balance,
something like this:
newBalance = p1.getBalance() -
square[newLlocation].getRent();
p1.setBalance(newBalance);
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 36
124. We are subtracting rents but not adding anything to the player's
balance.
Remember, our purpose is just to test the player object.
iv. print a message telling us the roll of the dice, the new
location, it's rent, and
new balance, such as:
Joe rolled 8. The Race Car is on Vermont Ave. The rent is $6.
Joe's now has $1,494.
Remember, this is the first part in building a Monopoly game in
Java so we are only testing the player
class object by moving the player on the board. Things like
picking a card if the player lands on Chance,
buying and selling properties, collecting $200 for passing Go,
and so on, are not part of this project. In a
real development situation, those things would be added in
another phase of the project once the
BoardSquare and Player objects work properly. Graphics (and
sound) would also be added later. Don’t
get carried away with fancy features at this point and make the
assignment harder than it needs to be.
Player (player for a Monopoly game)
- name: String
- token: String
125. - location: int
- balance: int
name of the player
racecar, wheelbarrow, battleship, top hat, etc.
the number of the square the player is on
initialized to zero
the player’s current bank balance
initialized to 1500
+ Player(): void
+ Player(String, String, int, int): void
+ getName(): String
+ getToken(): String
+ getLocation() int
+ getBalance() int
+ setName(String): void
+ setToken(String): void
+ setLocation(int): void
+ setBalance(int): void
+ toString:() String
(name, token, location, bank balance)
returns data about the player as a String