50 Chapter 4: Writing Classes
Chapter 4: Writing Classes
Lab Exercises
Topics Lab Exercises
Classes and methods Prelab Exercises
A Bank Account Class
Tracking Grades
GUIs: Buttons and
Textfields
Voting with Buttons
Calculating Body Mass Index
Chapter 4: Writing Classes 51
Prelab Exercises
1. Constructors are special methods included in class definitions.
a. What is a constructor used for?
b. How do constructors differ from other methods in a class?
3. Consider a class that represents a bank account.
a. Such a class might store information about the account balance, the name of the account holder, and an account
number. What instance variables would you declare to hold this information? Give a type and name for each.
b. There are a number of operations that would make sense for a bank account—withdraw money, deposit money,
check the balance, and so on. Write a method header with return type, name, and parameter list, for each such
ii. Deposit a given amount into the account. This changes the account balance, but does not return a value.
iii. Get the balance from the account. This does not change anything in the account; it simply returns the balance.
iv. Return a string containing the account information (name, account number, balance). This does not change
anything in the account.
v. Charge a $ 10 fee. This changes the account balance but does not return a value.
52 Chapter 4: Writing Classes
A Bank Account Class
1. File Account.java contains a partial definition for a class representing a bank account. Save it to your directory and study
it to see what methods it contains. Then complete the Account class as described below. Note that you won’t be able to
test your methods until you write ManageAccounts in question #2.
2. File ManageAccounts.java contains a shell program that uses the Account class above. Save it to your directory, and
complete it as indicated by the comments.
3. Modify ManageAccounts so that it prints the balance after the calls to chargeFees. Instead of using the getBalance
method like you did after the deposit and withdrawal, use the balance that is returned from the chargeFees method. You
can either store it in a variable and then print the value of the variable, or embed the method call in a println statement.
// *******************************************************
// Account.java
//
public Account(double initBal, String owner, long number)
{
balance = initBal;
name = owner;
acctNum = number;
}
// ——————————————–
Chapter 4: Writing Classes 53
// ——————————————–
public void deposit(double amount)
{
balance += amount;
}
// ——————————————–
// ——————————————–
public void chargeFee()
{
}
// ——————————————–
// Changes the name on the account
}
54 Chapter 4: Writing Classes
// ************************************************************
// ManageAccounts.java
//
// Use Account class to create and manage Sally and Joe’s
// bank accounts
// ************************************************************
public class ManageAccounts
{
public static void main(String[] args)
{
Account acct1, acct2;
//create account1 for Sally with $1000
acct1 = new Account(1000, “Sally”, 1111);
//create account2 for Joe with $500
//deposit $100 to Joe’s account
//print Joe’s new balance (use getBalance())
Chapter 4: Writing Classes 55
Tracking Grades
A teacher wants a program to keep track of grades for students and decides to create a student class for his program as
follows:
Each student will be described by three pieces of data: his/her name, his/her score on test #1, and his/her score on test#2.
There will be one constructor, which will have one argument—the name of the student.
1. File Student.java contains an incomplete definition for the Student class. Save it to your directory and complete the class
definition as follows:
2. File Grades.java contains a shell program that declares two Student objects. Save it to your directory and use the
3. Add statements to your Grades program that print the values of your Student variables directly, e.g.:
System.out.println(“Student 1: ” + student1);
This should compile, but notice what it does when you run it—nothing very useful! When an object is printed, Java looks
for a toString method for that object. This method must have no parameters and must return a String. If such a method
has been defined for this object, it is called and the string it returns is printed. Otherwise the default toString method,
56 Chapter 4: Writing Classes
// ************************************************************
// Student.java
//
// Define a student class that stores name, score on test 1, and
// score on test 2. Methods prompt for and read in grades,
// compute the average, and return a string containing student’s info.
// ************************************************************
import java.util.Scanner;
public class Student
{
//declare instance data
}
// ———————————————
//inputGrades: prompt for and read in student’s grades for test1 and test2.
//Use name in prompts, e.g., “Enter’s Joe’s score for test1”.
// ———————————————
public void inputGrades()
{
//add body of inputGrades
}
// ———————————————
//getAverage: compute and return the student’s test average
Chapter 4: Writing Classes 57
// ************************************************************
// Grades.java
//
// Use Student class to get test grades for two students
// and compute averages
//
// ************************************************************
public class Grades
{
Band Booster Class
In this exercise, you will write a class that models a band booster and use your class to update sales of band candy.
1. Write the BandBooster class assuming a band booster object is described by two pieces of instance data: name (a String)
and boxesSold (an integer that represents the number of boxes of band candy the booster has sold in the band fundraiser).
The class should have the following methods:
2. Write a program that uses BandBooster objects to track the sales of 2 band boosters over 3 weeks. Your program should
do the following:
Read in the names of the two band boosters and construct an object for each.
Representing Names
1. Write a class Name that stores a person’s first, middle, and last names and provides the following methods:
public Name(String first, String middle, String last)—constructor. The name should be stored in the case given;
don’t convert to all upper or lower case.
public String getFirst()—returns the first name
2. Now write a program TestNames.java that prompts for and reads in two names from the user (you’ll need first, middle,
and last for each), creates a Name object for each, and uses the methods of the Name class to do the following:
a. For each name, print
Drawing Squares
1. Write a class Square that represents a square to be drawn. Store the following information in instance variables:
size (length of any side)
x coord of upper left-hand corner
y coord of upper left-hand corner
2. Now write an applet DrawSquares that uses your Square class to create and draw 5 squares. This code should be very
simple; the paint method will simply create a Square and then draw it, repeated 5 times. Don’t forget to pass the
Graphics object to draw.
Chapter 4: Writing Classes 61
Voting with Buttons
Files VoteCounter.java and VoteCounterPanel.java contain slightly modified versions of PushCounter.java and
PushCounterPanel.java in listings 4.10 and 4.11 of the text. As in the text the program counts the number of times the button
is pushed; however, it assumes (“pretends”) each push is a vote for Joe so the button and variables have been renamed
appropriately.
2. Modify the program so that there are two candidates to vote for—Joe and Sam. To do this you need to do the following:
a. Add variables for Sam—a vote counter, a button, and a label.
3. Compile and run the program.
62 Chapter 4: Writing Classes
// ************************************************************
// VoteCounter.java
//
// Demonstrates a graphical user interface and event listeners to
frame.getContentPane().add(new VoteCounterPanel());
frame.pack();
frame.setVisible(true);
}
}
// ************************************************************
private JLabel labelJoe;
// ————————————————
// Constructor: Sets up the GUI.
// ————————————————
public VoteCounterPanel()
{
// **************************************************
private class JoeButtonListener implements ActionListener
{
//———————————————
// Updates the counter and label when Vote for Joe
// button is pushed
Calculating Body Mass Index
Body Mass Index (BMI) is measure of weight that takes height into account. Generally, a BMI above 25 is considered high,
that is, likely to indicate that an individual is overweight. BMI is calculated as follows for both men and women:
Files BMI.java and BMIPanel.java contain skeletons for a program that uses a GUI to let the user compute their BMI. This is
similar to the Fahrenheit program in listings 4.12 and 4.13 of the text. Fill in the code as indicated by the comments and
compile and run this program; you should see the BMI calculator displayed.
// ************************************************************
// BMI.java
//
// Sets up a GUI to calculate body mass index.
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
//*************************************************************
// BMIPanel.java
//
private JTextField height, weight;
private JButton calculate;
// —————————————————————–
// Sets up the GUI.
// —————————————————————–
//add the height label and height textfield to the panel
//add the weight label and weight textfield to the panel
//add the button to the panel
//add the BMI label to the panel
//add the label that holds the result to the panel
{
String heightText, weightText;
int heightVal, weightVal;
double bmi;
//get the text from the height and weight textfields
//Use Integer.parseInt to convert the text to integer values
}