// file GreeterTest2.java // CH's version 2 of the Greeter class adds an "instance variable" called "name" // which stores a reference to a String object, and a class constructor. Also // introduces the concept of method parameters and arguments // -> The instance var's of a class store the "state" of its objects (i.e. what // each object "knows"). // -> The constructor is called automatically whenever an object is created // ("instantiated") via the "new" operator. // // -> The purpose of a constructor is to set the state of the object being // constructed, by initializing its instance var's // Note that the Greeter constructor has a String "parameter variable" (i.e., // you must supply a String argument when creating a Greeter object. /** * Improved version of Greeter class allows user to "customize" the message * to be printed. */ class Greeter { private String name ; // note instance variable /** * Create a Greeter object with name supplied by user */ public Greeter(String aName) // constructor with String parameter var { name = aName ; // initializing the instance var to the } // value of the parameter /** * Print a personalized greeting */ public String sayHello() { String message = "Hello, " + name + "!" ; return message; } } /** * A test class for the Greeter class */ public class GreeterTest2 { public static void main(String[] args) { Greeter worldGreeter = new Greeter("World") ; System.out.println(worldGreeter.sayHello()) ; Greeter dollyGreeter = new Greeter("Dolly") ; System.out.println(dollyGreeter.sayHello()) ; } } /* program output Hello, World! Hello, Dolly! */