462 Object-Oriented Programming Chapter 9 Application class Test (Business web site)
Tuesday, September 4th, 2007462 Object-Oriented Programming Chapter 9 Application class Test (Fig. 9.9) uses this Point/Circle inheritance hierarchy. The application begins in method main by instantiating Circle object circle1 (line 11). This invokes the Circle constructor at line 15 of Fig. 9.8, which immediately invokes the Pointconstructor at line 15 of Fig. 9.7. The Point constructor outputs the values received from the Circle constructor by implicitly calling method toString and returns program control to the Circle constructor. Then the Circle constructor outputs the complete Circle by calling method toString. Notice that the first two lines of the output from this program both show values for x, y and radius. Polymorphism is once again causing the Circle s toString method to execute because it is a Circle object that is being created. When toString is invoked from the Point constructor, 0.0is displayed for the radiusbecause the radiushas not yet been initialized in the Circleconstructor. Circle object circle2 is instantiated next. Again, the Point and Circle constructors both execute. Notice, in the command-line output window, that the body of the Pointconstructor is performed before the body of the Circleconstructor, showing that objects are constructed inside out. 1 // Fig. 9.9: Test.java 2 // Demonstrate when superclass and subclass 3 // constructors and finalizers are called. 4 public class Test { 5 6 // test when constructors and finalizers are called 7 public static void main( String args[] ) 8 { 9 Circle circle1, circle2; 10 11 circle1 = new Circle( 4.5, 72, 29 ); 12 circle2 = new Circle( 10, 5, 5 ); 13 14 circle1 = null; // mark for garbage collection 15 circle2 = null; // mark for garbage collection 16 17 System.gc(); // call the garbage collector 18 } 19 20 } // end class Test Point constructor: Center = [72, 29]; Radius = 0.0 Circle constructor: Center = [72, 29]; Radius = 4.5 Point constructor: Center = [5, 5]; Radius = 0.0 Circle constructor: Center = [5, 5]; Radius = 10.0 Circle finalizer: Center = [72, 29]; Radius = 4.5 Point finalizer: Center = [72, 29]; Radius = 4.5 Circle finalizer: Center = [5, 5]; Radius = 10.0 Point finalizer: Center = [5, 5]; Radius = 10.0 Fig. 9.9Order in which constructors and finalizers are called. Fig. 9. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01