// Describe objects that have a first and last name, and an optional // middle name. class Name { private String first; // First name private String middle; // Middle name, or null if none private String last; // Last name // Make me with first name f, last name l, and no middle name. public Name (String f, String l) { this.first = f; this.last = l; } // Make me with first name f, middle name m, and last name l. public Name (String f, String m, String l) { this.first = f; this.middle = m; this.last = l; } // Return my first, middle, last names as a String. public String toString() { String result = this.first; if (this.middle != null) { result = result + " " + this.middle; } result = result + " " + this.last; return result; } // Test names with/without a middle name. public static void test () { Name n1 = new Name ("A", "B"); Name n2 = new Name ("A", "B", "C"); System.out.println (n1 + " and " + n2); } }
Simple test class to run the test method, which tests our Name class:
public class RunTest { public static void main (String[] args) { Name.test(); } }
A B and A B C