Java Programming Assignment

profileKhaledMaarof
Chapter9ClassesandObjectsinJavarevised.pdf

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

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

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

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

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

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

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

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 *******************************

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()

// 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;

} // 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

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:

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

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

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 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) {

// 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

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

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.

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

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

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.

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

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:

/* 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

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 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.

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 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:

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

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

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 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 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

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

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.

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

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

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

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 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) 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.

*/

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 = "";

} // 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()

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() {

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

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.

*/

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);

} // 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");

// 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);

} // 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");

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 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]

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

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

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.

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 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;

// 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();

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() {

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()

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()

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 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 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

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);

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

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 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

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:

• 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 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

{

// 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.

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

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;

// 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

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

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

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

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.

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 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

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 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? 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

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:

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

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 - 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