go to previous page   go to home page   go to next page

Answer:

When run, the program will print:

A Greeting!

to the monitor.


Steps in Program Execution

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 so when needed.

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 an object can be constructed without using the new operator. This is what the literal "A Greeting!" does.


QUESTION 20:

(Trick Question:) How many objects exist just before this program stops running? Click here for a