Designing a New Class

In this lesson, we will look at how to design a new Java class.

Design steps

Imagine that your current programming project involves the names of people. You could represent the names as strings, but you would prefer that they were objects of a data type specifically designed for names. You decide to create your own data type. You do this by writing a class definition.

In designing a class, you need to take the following steps:

  1. Name the class.
  2. Choose and name the data fields, indicating their data types.
  3. Describe the behaviors associated with objects of the class.
  4. Name the methods that will implement these behaviors.
  5. Specify the methods by writing a header and descriptive comments for each one.
  6. Write statements that use the methods and could appear in a client.
  7. Revise the method specifications, if necessary.

You would implement the class—by declaring the data fields and completing the body of each method—only after you are satisfied with the class design.

Let’s design the class Name.

Choosing the behaviors

For simplicity, we assume that a person’s name consists only of a first name and a last name. These two components make up the data associated with a Name object. We can label them first and last, respectively, and note that each is a string.

Here are some basic behaviors that our objects can have:

  • Set the first name to a given string.
  • Set the last name to a given string.
  • Set the first name and last name to given strings.
  • Get, or retrieve, the first name as a string.
  • Get the last name as a string.
  • Get the first and last names as one string.

To make our example a bit more interesting, we add the following behavior:

  • Give this object’s last name to a given Name object.

Specifying the methods

Having described the class’s behaviors, we name the methods and their parameters. We also choose the data types of the parameters and the values that the methods return. We can express the results of steps 4 and 5 by writing headers and descriptive comments for the methods in the context of a class definition, as the program given below shows. We have included a pair of braces for each method and have labeled each closing brace.

Get hands-on with 1200+ tech skills courses.