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() // 4a. an object has its own copy
{ // of this method.
System.out.println( greeting ); // 4b. the object's method uses
} // the data in its variable
} // 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 reference to the String is
// passed to the HelloObject
// constructor.
// A HelloObject is created.
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.
String
s are objects
(of course)
so they must be made with a constructor.
Remember that String
s are special because
an object can be constructed without using the new
operator.
This is what the literal "A Greeting!" does.