Chapter:Objects - Relation to classes - Exercises

From Juneday education
Jump to: navigation, search

Only one small exercise for this topic. But you did watch the video, didn't you?

Don't shoot the messenger

Create a new directory and change directory to the new one:

mkdir messenger
cd messenger

Create the following class in a file called

import javax.swing.JOptionPane;

public class Message {
  private String body;
  private String to;
  private String subject;

  public Message(String to, String subject, String body) { = to;
    this.subject = subject;
    this.body = body;

  private String formatContent() {
    return new StringBuilder("<html>")
      .append("<strong>To: </strong>")
      .append("<br><strong>Subject: </strong>")
  public void send() {

  public void cancel() {
                         "Your message was cancelled.",
                         "Message cancelled",

Create the following class in a file called

public class Messenger {
  public static void main(String[] args) {
    String to = System.getProperty("");
    Message messageToMyself =
      new Message(to,
                  "Hello, " + to,
                  "Here's a small message");

Messenger is the program. It creates an object using the class Message. It sends the message send() to the object.

Compile ( will also be compiled automatically):


Run the Messenger program:

java Messenger

What happened? Can you follow the call messageToMyself.send(); from the program? Look in

You don't need to understand the code! We just wanted you to see for yourself what the relationship between an object and its class definition is.

Now, change the line in from messageToMyself.send(); to messageToMyself.cancel();. Re-compile the same way as you compiled it before, and run the program again. What happened?

Can you find the code which produced the result? Again, you don't need to understand this. We just wanted to get you curious about code and its relation to the two files.

Study the indentation of the class Messenger. Note where curly braces are put, and what lines are aligned horizontally (start at the same column).

How many blocks does the Messenger class contain?

The very last right curly brace (}) closes the outer block. Where is its corresponding left curly brace?

Move on to the next chapter for more!


Source code for the exercise

Further reading

Where to go next

Next chapter is: Objects_-_Creating

« PreviousBook TOCNext »