Learn Object-Oriented Java the Hard Way

Exercise 6: Accessing Fields in Methods

In this exercise, we are going to look in closer detail at the concept of an object having fields and methods that access those variables. This was introduced in the OOP-version of the previous exercise.

Here is the source code for the object, which will take a phrase and a number and produce a String with the specified number of copies of that message.

PhraseRepeater.java
 1 public class PhraseRepeater {
 2 
 3     String phrase;
 4     int repeats;
 5 
 6     public void setValues( String p, int r  ) {
 7         phrase = p;
 8         repeats = r;
 9     }
10 
11     public String getRepeatedPhrase() {
12         String result = "";
13         for ( int i=0; i<repeats; i++ )
14             result += phrase;
15         return result;
16     }
17 }

This class has two fields / instance variables, a String named phrase and an int named repeats. Remember that if we were to instantiate several versions of this object in a driver, each instance of the object would have its own copies of both fields.

“Instance variables” are variables defined in a class but outside of any method. A “field” is just a generic name for a member of a class. They mean pretty much the same thing, so I will use them interchangably in this book.

In case you didn’t remember it from the previous exercise, these instance variables belong to the whole class, so all the methods in the object can access them.

Lines 6-9 implement a method called setValues(). This method receives two values from the outside world, a String we’re going to call p and an integer we will call r.

On line 7 we store a copy of p’s value into our instance variable phrase, and on the next line we store a copy of r’s value into repeats. After line 9, the parameter variables p and r go away; those names don’t have any meaning outside of this method. This method is void, so it doesn’t return any value to the outside world.

Lines 11 through 16 have the implementation of a method called getRepeatedPhrase(), which builds up and then returns a copy of the value of a String.

On line 12 we start with a new String result, which is initialized to “the empty String” (that’s what we call a String value with no characters in it).

Line 13 sets up a for loop that will execute its body repeats-many times. That is, if repeats has a 4 in it, the loop will run through four times. There are no curly braces in this loop, so the body of the loop is just a single line: result += phrase;, which adds a copy of the value of phrase to the end of whatever is already in result.

After the loop finishes, result now has several copies of the phrase in it. Notice that just like the previous method, this method was able to access the fields.

Finally, on line 15, a copy of the String in the local variable result is returned to the outside world. This method returns a String, which is why the first line of the method says public String getRepeatedPhrase() instead of public void getRepeatedPhrase().

(Note that the method does not return the variable result itself; it merely returns a copy of the value that was in that variable.)

Okay, here’s the driver code:

PhraseRepeaterDriver.java
 1 import java.util.Scanner;
 2 
 3 public class PhraseRepeaterDriver {
 4     public static void main( String[] args ) {
 5         Scanner keyboard = new Scanner(System.in);
 6 
 7         System.out.print("Enter a message: ");
 8         String msg = keyboard.nextLine();
 9         System.out.print("Number of times: ");
10         int n = keyboard.nextInt();
11 
12         PhraseRepeater pr = new PhraseRepeater();
13         pr.setValues(msg, n);
14         System.out.println( pr.getRepeatedPhrase() );
15     }
16 }

What You Should See

The first ten lines of the driver are pretty straightforward if you’ve been coding in Java for a bit: they allow the human to enter in some values which get stored into local variables msg and n.

Then on line 12 we instantiate a single copy of the PhraseRepeater object and store a reference to it in the variable pr.

Then on line 13 we call that object’s setValues() method, passing in copies of our local variables. The driver does not know that the instance variables inside the object are named phrase and repeats. The driver does not care what they are named.

The driver does not know that the parameters to the setValues() method will be called p and r. It makes no difference to the driver. Only the object cares what those variables are called.

This sort of not-caring is one of the reasons that object-oriented programming makes it easier to write very large complicated programs and debug them.

Anyway, the last useful line of the driver program is line 14, which calls the getRepeatedPhrase() method. That method returns a String, and the String that gets returned is fed to println() for… printing.

Notice that the setValues() method changes something inside the object. The fields in that object are different after the method call. Thus methods that change the internal state of an object in some way are often called “modifier methods” or “mutator methods”.

On the other hand, the getRepeatedPhrase() method does not change anything about the internals of the object; both instance variables are used but they are not modified. But the method does return a value that lets you know something about the internal state of the object. Methods like this are often called “accessor methods” because they allow the driver to access the fields in some way.


“Learn Object-Oriented Java the Hard Way” is ©2015–2016 Graham Mitchell