|  | 
         
          | The example below illustrates the two different ways to instantiate 
              a class that contains two constructors. A class can possess any 
              number of constructors and thus allow great flexiblity in the initialization 
              of an instance of that class. (In Chapter 4 we discuss this technique 
              of overloading constructors and methods.) 
              
                 
                  | ConstructorsApplet.java (Output goes to browser's Java 
                    console.)
 |   
                  | public 
                      class 
                      ConstructorsApplet extends 
                      java.applet.Applet {
 public 
                      void init () {
 // Create an instance of the Test 
                      class using
 // its no 
                      argument constructor.
 Test test = new 
                      Test ();
 
 // Here a new Test object is created 
                      using
 // its 
                      one 
                      argument constructor.
 test 
                      = new Test (i);
 }
 
 // 
                      Paint message in Applet window.
 public void paint 
                      (java.awt.Graphics g) {
 g.drawString ("ConstructorsApplet", 
                      10, 20);
 }
 }
 
 // This Test class has two constructors.
 class 
                      Test
 {
 Test () {
 System.out.println ("In Test ()");
 System.out.println 
                      ("m = " + m);
 System.out.println 
                      ();
 }
 
 // 
                      Note that placement of a data field in the class
 // definition is not important
 int 
                      m;
 Test 
                      (int j) {
 m 
                      = j;
 System.out.println 
                      ("In Test (int j)");
 System.out.println 
                      ("m = " + m);
 System.out.println 
                      ();
 }
 }
 |   
                  |  |    Latest update: Oct. 19, 2004 |  |  |