Activity 3.3 - Writing a toString method

Topic

In this activity we shall write a toString method that overrides the one inherited from Object.

Materials

In addition to the Solution document, the project for this activity contains two classes:

Task

The RoomID class is to be provided with a method

String toString() 

that will return a string saying that the object is a room ID and describing the values of the instance variables (the blockName and roomNumber of the RoomID object).

Instructions

  1. Run the project and you will see the output resulting from using the inherited toString method.
  2. Open the class RoomID and insert a toString method that returns a more informative string.
  3. Run the project to check that the method works as you intend.

Notes

You may have noticed that the editor has added a lightbulb symbol to the left of the equals method, as shown in the following screenshot.


a lightbulb appears in the editor left-hand margin

If you click on this symbol you will see a suggestion to add an @Override annotation.


clicking on add Override annotation

If you click on this hint, the @Override annotation is added for you. This annotation indicates that the following method is intended to override an inherited method. If you use this annotation and the method following it does not override any methods, a compilation error will result. This is a useful check that you are doing what you intended to do, and also a reminder when reading code that you are overriding an inherited method.

You may like to add this annotation whenever you intend to override a method. For example, you may like to use it now on your toString method. You can type it in manually if you want to.

There are also other useful hints available using the lightbulb symbol, but you are not required to use such hints in assignments. Using such hints may lead you to a different solution than the one intended by a question.