Skip to main content
Logo image

Java, Java, Java: Object-Oriented Problem Solving, 2022E

Section 2.4 Class Definition

To program in Java the main thing you do is write class definitions for the various objects that will make up the program. A class definition encapsulates its objects’ data and behavior. Once a class has been defined, it serves as a template, or blueprint, for creating individual objects or instances of the class.
A class definition contains two types of elements: variables and methods. Variables are used to store the object’s information. Methods are used to process the information. To design an object you need to answer five basic questions:
  1. What role will the object perform in the program?
  2. What data or information will it need?
  3. What actions will it take?
  4. What interface will it present to other objects?
  5. What information will it hide from other objects?

Subsection 2.4.1 The RiddleClass

Recall our definition of the Riddle class from Chapter 1, which is summarized in the UML diagram in Figure 2.4.1. A Riddle has two attributes, question and answer. Each of these variables stores a String. It contains three methods, the Riddle() constructor, the getQuestion() and getAnswer() methods.
Figure 2.4.1. The Riddle class.
The instance variables question and answer are designated as private(\(-\)), but the Riddle(), getQuestion() and getAnswer() methods are designated as public (\(+\)). These designations follow two important object-oriented design conventions, whose justification will become apparent as we discuss the Riddle class:
Listing 2.4.2 shows the Java class definition that corresponds to the design given in the UML diagram. It contains the two private instance variables and defines the three public methods listed in the UML diagram.
public class Riddle {
  private String question; //Instance variables
  private String answer;

  public Riddle(String q, String a) {  // Constructor
    question = q;
    answer = a;
  } // Riddle constructor

  public String getQuestion() {  // Instance method
    return question;
  } // getQuestion()

  public String getAnswer() {   // Instance method
    return answer;
  } //getAnswer()
} //Riddle class
Listing 2.4.2. Definition of the Riddle class.
The private and public modifiers are known as access modifiers. They control access to an object’s elements, such as its variables or methods, by other objects — preventing access to private elements and permitting access to the public elements. Note also that the Riddle class itself is declared public, which allows access to its objects through its public variables and methods.
Recall that a class definition is like a blueprint or a cookie cutter. The Riddle class defines the type of information (attributes) that each Riddle object has, but it doesn’t contain any actual values. It defines the methods (operations) that each Riddle object can perform, but it doesn’t actually perform the methods.

Subsection 2.4.2 The RiddleUser Class

To test Riddle we need to define a main() method, which can be defined either within the Riddle class itself or in a second class.
One advantage of using a second class is that it gets us in the habit of thinking about the need for a separate object to serve as a user interface. A user interface is an object that handles the interaction between a program’s user and the rest of the program’s tasks ("Figure 2.4.5).
We use the general term computational object to distinguish the rest of the program’s tasks from its user interface. The Riddle's task is just to manage simple riddles.
Figure 2.4.5. The RiddleUser class.
Thus, as shown in Figure 2.4.6, this program will involve interaction between two types of objects: a RiddleUser and one or more Riddles. The relationship between them, represented by a one-way “Uses” arrow,is that the RiddleUser will create a Riddle instance and use its methods to display a riddle for the user.
Figure 2.4.6. This UML class diagram represents an association between the RiddleUser and Riddle classes. The RiddleUser class will use one or more objects of the Riddle class.
This design employs the divide-and-conquer principle. The problem has been divided into two distinct tasks, the user interface (RiddleUser) and the computation (Riddle). Each type of object manages its own task and they work together to solve a problem.
Because almost all of our programs will involve some form of a user interface, we will follow this design approach throughout the book. It will serve us well. especially as our problems and our programs become more complex.

Subsection 2.4.3 Object Instantiation: Creating Riddle Instances

Listing 2.4.7 shows the complete definition of the RiddleUser class, which serves as a very simple user interface. It creates two Riddle objects, named riddle1 and riddle2. It then asks each object to request each riddle’s question and answer and displays them on the console.
public class RiddleUser
  public static void main(String argv[])
  { Riddle riddle1 = new Riddle(
      "What is black and white and red all over?",
      "An embarrassed zebra.");
    Riddle riddle2 = new Riddle(
      "What is black and white and read all over?",
      "A newspaper.");
    System.out.println("Here are two riddles:");
    System.out.println("The answer to the first riddle is:");
    System.out.println("The answer to the second is:");
  } // main()
} // RiddleUser
Listing 2.4.7. The RiddleUser class.

Activity 2.4.1.

Run the code below. Add another Riddle to RiddleUser main and print it out.
Let’s now discuss the statements that make up RiddleUser’s main() method. The following statements use the Riddle() constructor to create, or instantiate, two instances of the Riddle class:
Riddle riddle1 = new Riddle(
     "What is black and white and red all over?",
     "An embarrassed zebra.");
Riddle riddle2 = new Riddle(
    "What is black and white and read all over?",
     "A newspaper.");
Note how the constructor gives each object a pair of String s that serve as the values of their two instance variables. Each object has its own question and its own answer, and each object has its own unique name, riddle1 and riddle2.

Subsection 2.4.4 Interacting with Riddles

Once we have created Riddle instances with values assigned to their question and answer instance variables, we can ask each riddle to tell us either of its values. The following expression is an example of a method call:
Calling (or invoking) a method is a means of executing its code. The above method call just gets the String value that is stored in the question instance variable of riddle1.
If we want to display the value of riddle1’s question, we can embed this method call within a println() statement
This tells the System.out object to execute its println() method, which displays the string given to it by riddle1 on the console. Thus, the output produced by this statement will be
What is black and white and red all over?

Subsection 2.4.5 Define, Create, Use

As our Riddle example illustrates, writing a Java program is a matter of three basic steps:
  • Define one or more classes (class definition).
  • Create objects as instances of the classes (object instantiation).
  • Use the objects to do tasks (object use).
The Java class definition determines what information will be stored in each object and what methods each object can perform. Instantiation creates an instance and associates a name with it in the program. The object’s methods can then be called as a way of getting the object to perform certain tasks.

Exercises Self-Study Exercises

Identify the following elements in the Riddle class (Figure 2.4.1).
1. Class Name.
What’s the name of the class in Figure 2.4.1)?
2. Riddle Instance Variables.
3. Riddle Methods.
4. Riddle Instances.
5. Riddle Method Calls.
6. Riddle Qualified Names.
You have attempted of activities on this page.