next up previous
Next: 1.5 Loose Ends Up: 1.4 Java Classes and Previous: 1.4.6 The Command Pattern

1.4.7 Help Methods and Visibility

The coding of non-trivial methods often involves the use of auxiliary methods called ``help'' methods. The specified operation may be easily derivable from another operation that has a cleaner computational definition. For example, assume that we want to modify the ``printing'' (as defined in toString() of DeptDirectory instances to include a header and footer for the listing.

In this case, we can convert the old toString method to a help method named toStringEntries and redefine toString in DeptDirectory as follows:

abstract class DeptDirectory {
  ...
  public String toString() {
    return "Department Directory\n\n" + toStringEntries() + "\n***";
  }
  abstract String toStringEntries();
}

class Empty extend DeptDirectory{
  ...
  String toStringEntries() {
    return "";      
  }
}

class Cons extends DeptDirectory {
  ...
  String toStringEntries() {
    return first + rest.toStringEntries();
  }
}

Since help methods are defined strictly for the use of code within the class, we would like to prevent the definition from ``leaking'' outside the class. Java provides a mechanism for prevents such leaks. Class members can be assigned one of four visibility levels private, default, protected or public. private members are visible only within the class in which they are defined. protected members are visible the the in the package containing the defining class and in subclasses of the defining class. public members are visible everywhere. The default protection attribute is visibility within the package containing the defining class.

The private attribute is well-suited to help methods that aren't required in subclasses. If subclass code references the member, then the protected attribute is required.


next up previous
Next: 1.5 Loose Ends Up: 1.4 Java Classes and Previous: 1.4.6 The Command Pattern
Robert Cartwright, Spring 1999