Skip to main content
Engineering LibreTexts

2.3: Class Definition

  • Page ID
    15065
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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:

    What role will the object perform in the program?

    What data or information will it need?

    What actions will it take?

    What interface will it present to other objects?

    What information will it hide from other objects?

    The Riddle Class

    Recall our definition of the Riddle class from Chapter 1, which is summarized in the UML diagram in Figure 2.11. A Riddle has two attributes, question and answer. Each of these variables stores a string of characters, which Java treats as data of type String. The Riddle class contains three methods. The Riddle() constructor method assigns initial values (qand a) to its question and answer variables. The getQuestion() and getAnswer() methods return the data stored in question ands answer respectively.

    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:

    Figure [fig-riddleclass2] shows the Java class definition that corresponds to the design given in the UML diagram. It contains the

    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

    two private instance variables and defines the three public methods listed in the UML diagram. In a Java class definition, access to a class element, such as a variable or a method, is controlled by labeling it with either the private, or public access modifier. An access modifier is a declaration that controls access to a class or one of its elements. Note also that the Riddle class itself is declared public. This lets other classes have access to the class and to its public variables and methods.

    Recall that a class is like a blueprint or a cookie cutter. The Riddle class defines the type of information (attributes) that each individual Riddle has, but it doesn’t contain any actual values. It defines the methods (operations) that each Riddlecan perform, but it doesn’t actually perform the methods. In short, a class serves as a template, providing a detailed blueprint of the objects (or instances) of that class.

    The RiddleUser Class

    Now that we have defined the Riddle class, we can test that it works correctly by creating Riddle objects and “asking” them to tell us their riddles. To do this we need to define a main() method, which can be defined either within the Riddleclass itself or in a second class named something like RiddleUser.

    One advantage of using a second class is that it gets us in the habit of thinking about the need for a separate class to serve as a user interface, with a separate set of tasks from the Riddle class. A user interface is an object or class that handles the interaction between a program’s user and the rest of the program’s computational tasks. This concept is illustrated in Figure 2.13. Note that we use the general term computational object to distinguish the rest of the program’s computations from the user interface. Obviously, the exact nature of the computation will vary from program to program, just as will the details of the user interface. The computation done by our Riddle class is just the storing and displaying of a riddle’s question and answer.

    By separating user interface tasks from riddle tasks this design employs the divide-and-conquer principle: the RiddleUser class will create Riddle objects and handle interactions with the user, and the Riddle class will handle the storing and transmission of riddle information. Thus, as shown in Figure [fig-p63f2], this particular Java program will involve interaction between two types of objects: a RiddleUser and one

    or more Riddles. Note that we characterize the relationship between Riddle and RiddleUser with a one-way arrow labeled “Uses.” This is because the RiddleUser will create an instance of Riddle and use its methods to display (for the user) a riddle.

    Because almost all of our programs will involve some form of a user interface, we can generalize this design approach and follow it throughout the book. One way to think about this approach is as a division of labor between a user interface class and a second computational class, which performs whatever computations are needed by the particular program. In this case the computations are the simple Riddle methods that we have defined. In subsequent programs the computations will become more complex, which will make all the more clear that they should be separated from the user interface.

    Object Instantiation: Creating Riddle Instances

    Figure [fig-riddleuser] 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(riddle1.getQuestion());
        System.out.println(riddle2.getQuestion());
        System.out.println("The answer to the first riddle is:");
        System.out.println(riddle1.getAnswer());
        System.out.println("The answer to the second is:");
        System.out.println(riddle2.getAnswer());
      } // main()
    } // RiddleUser

    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 Strings 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.

    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:

    riddle1.getQuestion()

    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

    System.out.println(riddle1.getQuestion());

    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?

    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.

    Identify the following elements in the Riddle class (Fig. [fig-riddleclass2]):

    • The name of the class.
    • The names of two instance variables.
    • The names of three methods.

    Identify the following elements in the RiddleUser class (Fig. [fig-riddleuser]):

    • The names of two Riddle instances.
    • All six method calls of the Riddle objects in the program.
    • Two examples of qualified names.

    This page titled 2.3: Class Definition is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by Ralph Morelli & Ralph Wade via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.