5.4 Accessor Methods
One key aspect of writing classes in Java is that you can control how the class is used. As mentioned earlier, instance variables are kept private in your Java classes, but that doesn’t mean that users can’t access them via public methods. Access to variables is controlled by the developer through accessor methods.
An accessor method is a method that is used to return the value of an instance (or static) variable to the user. Since the method is returning a value to the user, the method header should contain the return type in place of the keyword void.
When creating accessor methods there is a common convention you should follow. When naming your method you should always use this format: get[Variable Name]
for the name. Some examples of this would be: getWidth()
, getHeight()
, and getColor()
. As a result of this naming convention, accessor methods are sometimes referred to as “getter” methods.
Here is an examples of how this would look:
As a non-void method, the accessor method returns a single value. This value needs to be compatible with the return type in the method header, for example a string needs to return a string, or a double return type needs to return a number (an int or double is compatible with a double).
When returning a value, a copy of that value is returned to the calling method, whether the value is a primitive or an object. This is referred to as “return by value.”
As soon as the return keyword is used, the program returns to the point immediately following where the method was called. This can be used to return a value or to interrupt the progress execution and end the method execution.
The toString
method is a specific method that is used to return a string representation of the object. The method is often included in many classes as a way to override the default object description and provides a description of the object. It will generally include some of the values stored in instance variables, or a calculation with those values, but it doesn’t have to.
While the method can be called with using the standard dot syntax, such as obj.toString()
, the method is also called by default for print statements.
For example, if there is a Shape
class that has a toString method, the toString would be called int he following situation:
-
Incorrect
Correct
No Answer was selected
Invalid Answer
Which of the following method signatures would be appropriate as an accessor method for an
String
instance variable calledname
?
The TextMessage
class was created to save text messages. Currently, the class has a constructor and a toString
.
Continue adding to this class by adding four accessor methods: