CS 1063 Lab 4:
Using and Modifying a Class
The BirthdaySong
Class
Objectives
- Demonstrate your ability to use a class given the public interface
- Construct and use Objects
- Modify the behavior of a class
Hand-in Requirements
All projects and laboratories will be submitted electronically through
webCT. Zip up your entire project directory to submit as the
source. (Right click on the project folder and follow
the SentTo link.) The project directory should include
the following:
- Public Interface as a word or plaintext document
- BirthdaySong.java
- BirthdaySongTest.java
Details
You will modify a class named BirthdaySong. This
class has a method named sing that prints the words for Happy
Birthday. However this song does not mention the name of the
birthday person. We would like it to sing to a person that the
client designates. Your job will be to test and modify this
class.
public class BirthdaySong {
// Constructor
public BirthdaySong() {
}
|
public void sing() {
System.out.println("Happy birthday to you");
System.out.println("Happy birthday to you");
System.out.println("Happy birthday dear ");
System.out.println("Happy birthday to you");
}
|
}
|
Part 1: Write the public interface for the BirthdaySong
class and be sure to add comments to each method
Part 2: Setup:
- Project/Folder name: BirthdaySong
- New class with main method: BirthdaySongTest
public class BirthdaySongTest {
public static void main(String[] args) {
}
}
- Save the class in the BirthdaySong folder.
- Download the following file
BirthdaySong.java
and save in in the BirthdaySong folder.
- Open BirthdaySong.java in DrJava.
- Click on BirthdaySongTest in the Navigator pane (on the
left).
- Compile and run.
- Save the project.
Part 3: Modify and Test:
Test the BirthdaySong class.
- Instantiate a BirthdaySong object named b1.
- Have b1 print the song.
After you have checked to see if your output is correct, comment out
the above two lines using /* and */
Modify the BirthdaySong
class so that it sings the song to a person whose name is supplied by
the client.
- Add a private String instance variable myName.
- Modify the constructor so that its parameter is String
name and assign name to myName
in
the constructor.
- Modify the sing method so that it uses myName.
Happy birthday to you
Happy birthday to you
Happy birthday dear <myName here> !!!
Happy birthday to you
Don't forget to print the !!!
- Add a method setName that changes myName to a
given name from the client. The method stub would look like
this:
public void setName(String name) {
// Your code here
}
-
Test your modifications.
- Instantiate a BirthdaySong object named b2 using the
name "Grace" to sing to.
- Have b2 sing.
- Set the name for b2 to "Blaise" using the
setName method.
- Have b2 sing again.
- Set the name for b2 to "Alan" using the setName
method.
- Have b2 sing again.