6.1 Consider the following task: You are on vacation and want to send postcards
ID: 3760713 • Letter: 6
Question
6.1 Consider the following task: You are on vacation and want to send postcards to your friends. A typical postcard might look like this:
You decide to write a computer program that sends postcards to various friends, each of them with the same message, except that the first name is substituted to match each recipient.
What "black box" (class that will be used to build objects of its type) can you identify that will allow you to send your greeting?
6.2 We want to be able to write a program that will use our Postcard class to send postcards with the same message to different recipients.
The following class implements a Postcard. Notice that we do not set the recipient in the constructor because we want to be able to change the recipient, and keep the same message and sender. What method would you add to support this functionality? Implement the method.
// Your method here
6.3 Add a print method to the Postcard class to display the contents of the postcard on the screen. Use the instance variables message, sender, and recipient defined in the last step when you implement the method.
6.4 Try out your class with the following code:
What is the output of your program?
Explanation / Answer
public class PostcardPrinter
{
public static void main(String[] args)
{
String text = "I am having a great time on the island of Java. Weather is great. Wish you were here!";
Postcard postcard = new Postcard("Janice", text);
postcard.setRecipient("Sue");
postcard.print();
postcard.setRecipient("Tim");
postcard.print();
}
}
package mani;
public class Postcard
{
private String message;
private String sender;
private String recipient;
public Postcard(String aSender, String aMessage)
{
message = aMessage;
sender = aSender;
recipient = "";
}
public void setRecipient(String s){
recipient=s;
}
public void print(){
String s="Dear "+recipient;
s=s+": "+message;
s=s+" Love, ";
s=s+sender;
System.out.println(s);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.