When run, the program will print:
A Greeting!
to the monitor.
Here is how the program does this:
class HelloObject // 3a. the class definition is
{ // used to construct the object.
String greeting;
HelloObject( String st ) // 3b. the constructor is used to
{ // initialize the variable.
greeting = st;
}
void speak()
{
System.out.println( greeting );
}
}
class HelloTester
{
public static void main ( String[] args ) // 1. main starts running
{
HelloObject anObject =
new HelloObject("A Greeting!"); // 2. the String "A Greeting"
// is constructed.
// 3. a HelloObject is created.
// A reference to the String
// is passed to the constructor.
anObject.speak(); // 4. the object's speak()
// method is activated.
}
}
You usually don't think about what is going on in such detail. But you should be able to do it when you need to.
Notice that a String object containing "A Greeting!" is constructed before the HelloObject constructor is even called. Strings are objects (of course) so they must be made with a constructor. Remember that Strings are special because something like "A Greeting!" constructs an object without using the new operator.