Before you begin

This unit is part of the “Intro to Java programming” learning path. Although the concepts discussed in the individual units are standalone in nature, the hands-on component builds as you progress through the units, and I recommend that you review the prerequisites, setup, and unit details before proceeding.

Unit objectives

  • Know how to hand-code the declaration of an accessor method pair
  • Learn correct syntax for calling methods with or without parameters
  • Know how to nest method invocations

Accessor methods

The getters and setters that you saw in action at the end of Unit 5 are called accessor methods. (Quick review: A getter is a method for retrieving the value of an attribute; a setter is a method for modifying that value.) To encapsulate a class’s data from other objects, you declare its variables to be private and then provide accessor methods.

The naming of accessors follows a strict convention known as the JavaBeans pattern. In this pattern, any attribute Foo has a getter called getFoo() and a setter called setFoo(). The JavaBeans pattern is so common that support for it is built into the Eclipse IDE, as you saw when you generated getters and setters for Person.

Accessors follow these guidelines:

  • The attribute is always declared with private access.
  • The access specifier for getters and setters is public.
  • A getter doesn’t take any parameters, and it returns a value whose type is the same as the attribute it accesses.
  • Setters take only one parameter, of the type of the attribute, and do not return a value.

Declaring accessors

By far the easiest way to declare accessors is to let Eclipse do it for you. But you also need to know how to hand-code a getter-and-setter pair.

Suppose I have an attribute, Foo, whose type is java.lang.String. My complete declaration for Foo (following the accessor guidelines) is:


private String foo;
public String getFoo() {
  return foo;
}
public void setFoo(String value) {
  foo = value;
}

Notice that the parameter value passed to the setter is named differently than if it had been Eclipse-generated (where the parameter name would be the same as the attribute name — for example, public void setFoo(String foo)public void setFoo(String foo)). On the rare occasions when I hand-code a setter, I always use value as the name of the parameter value to the setter. This eye-catcher — my own convention, and one that I recommend to other developers — reminds me that I hand-coded the setter. If I don’t use Eclipse to generate getters and setters for me, I have a good reason. Using value as the setter’s parameter value reminds me that this setter is special. (Code comments can serve the same purpose.)

Calling methods

Invoking — or calling— methods is easy. The testPerson method at the end of Unit 5, for example, invokes the various getters of Person to return their values. Now you’ll learn the formal mechanics of making method calls.

Method invocation with and without parameters

To invoke a method on an object, you need a reference to that object. Method-invocation syntax comprises:

  • The object reference
  • A literal dot
  • The method name
  • Any parameters that need to be passed

The syntax for a method invocation without parameters is:


objectReference.someMethod();

Here’s an example:


Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE");
p.getName();

The syntax for a method invocation with parameters is:


objectReference.someOtherMethod(parameter1, parameter2, . . ., parameterN);

And here’s an example (setting the Name attribute of Person):


Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE");
p.setName("Jane Q Author");

Remember that constructors are methods, too. And you can separate the parameters with spaces and newlines. The Java compiler doesn’t care. These next two method invocations are equivalent:


new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE");


new Person("Joe Q Author",// Name
  42,     // Age
  173,    // Height in cm
  82,     // Weight in kg
  "Brown",// Eye Color
  "MALE");// Gender

Notice how the comments in the second constructor invocation make it more readable for the next person who might work with this code. At a glance, that developer can tell what each parameter is for.

Nested method invocation

Method invocations can also be nested:


Logger l = Logger.getLogger(Person.class.getName());
l.info("Name: " + p.getName());

Here you pass the return value of Person.class.getName() to the getLogger() method. Remember that the getLogger() method call is a static method call, so its syntax differs slightly. (You don’t need a Logger reference to make the invocation; instead, you use the name of the class as the left side of the invocation.)

That’s all there is to method invocation.

Test your understanding

  1. Which answer best describes the Java Beans pattern?

    1. It’s where you use the Java API to write any application that’s compliant with the Java specification.
    2. It’s a particular way of writing code with regard to how to declare, access, and set values on the attributes of a Java object.
    3. The JavaBeans pattern cannot actually be coded; it exists only as an ideal standard.
    4. None of the above.
  2. What’s the difference between invoking a method and calling a method?

    1. Invoking a method is writing the method’s code to use the static keyword. Calling a method is only for instance-based objects.
    2. Calling a method means to document it thoroughly, whereas invoking the method is done through Java source code.
    3. There’s no difference; calling a method and invoking a method are synonyms for “executing a method.”
    4. The difference only manifests when the code is written in Python or Ruby.
    5. None of the above
  3. Constructors are not methods.

    1. It depends on the compiler context.
    2. False
    3. Sometimes, except that constructors cannot have parameters.
    4. True
  4. Programming problem: Implement the toString() method on Person. Use the code for the Person class from Question 5 in Unit 4‘s quiz. Use the Javadoc for Object.toString() for a description of what toString() is supposed to do.

  5. Programming problem: Write a JUnit test case to test the toString() method on Person from Question 4. Add your test method to the PersonTest class that you created in Unit 5.

Check your answers

  1. Which answer best describes the Java Beans pattern? It’s a particular way of writing code with regard to how to declare, access, and set values on the attributes of a Java object.

  2. What’s the difference between invoking a method and calling a method? There’s no difference. Calling a method and invoking a method are synonyms for “executing a method.”

  3. Constructors are not methods. False.

  4. Programming problem: Implement the toString() method on Person. Use the code for the Person class from Question 5 in Unit 4‘s quiz. Use the Javadoc for Object.toString() for a description of what toString() is supposed to do.

    package com.makotojava.intro;
    
    public class Person {
     private String name;
     private int age;
     private int height;
     private int  weight;
     private String eyeColor;
     private String gender;
    
     public String getName() { return name; }
     public void setName(String value) { name = value; }
     // Other getter/setter combinations...
     public int getAge() { return age; }
     public void setAge(int value) { age = value; }
    
     public int getHeight() { return height; }
     public void setHeight(int value) { height = value; }
    
     public int getWeight() { return weight; }
     public void setWeight(int value) { weight = value; }
    
     public String getEyeColor() { return eyeColor; }
     public void setEyeColor(String value) { eyeColor = value; }
    
     public String getGender() { return gender; }
     public void setGender(String value) { gender = value; }
    
     public String toString() {
       String ret = "Name: " + getName() + ", " +
          "Height: " + getHeight() + ", " +
          "Weight: " + getWeight() + ", " +
          "Eye Color: " + getEyeColor() + ", " +
          "Gender: " + getGender();
    
       return ret;
     }
    }
    
  5. Programming problem: Write a JUnit test case to test the toString() method on Person from Question 4. Add your test method to the PersonTest class that you created in Unit 5.

package com.makotojava.intro;

import static org.junit.Assert.*;

import java.util.logging.Logger;

import org.junit.Test;

public class PersonTest {

    @Test
    public void testPerson() {
        .
        .
        .
    }

    @Test
    public void testToString() {
      Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE");

      Logger l = Logger.getLogger(PersonTest.class.getName());

      l.info("toString(): " + p.toString());
    }

Previous: Your first Java classNext: Strings and operators