| The example below illustrates how a static property, here a double 
              type variable, can be accessed before an instance of that class 
              is created.  We also show that if that static variable is changed, it changes 
              for all instances of that class. Whereas, an instance variable ("m"), 
              will hold different values in different classes. 
              
                 
                  | StaticApplet.java (Output goes to browser's Java 
                    console.)
 |   
                  | public 
                      class StaticApplet extends java.applet.Applet{
 public void init() {
 
 System.out.println ("   
                      Static vs Instance Variables");
 
 // Access static variable via the 
                      class name Test.
 System.out.println (" Before an 
                      instance of Test created:");
 System.out.println ("  pi 
                      = " + Test.pi);
 
 //Create an instance of the Test 
                      class
 Test test = new Test ();
 Test testa = new Test (456);
 
 System.out.println (" Create two 
                      instances of Test:");
 // Access instance variable
 System.out.println ("  1st 
                      instance j = " + test.m);
 
 System.out.println ("  2nd 
                      instance j = " + testa.m);
 
 
 // If a new value assigned to a 
                      static variable
 Test.pi = 3.1416;
 System.out.println (" Set Test.pi 
                      to 3.1416");
 System.out.println (" Value of pi 
                      in each Test object after change:");
 
 // It changes for all instances.
 System.out.println ("  test.pi  = 
                      " + test.pi);
 System.out.println ("  testa.pi 
                      = " + testa.pi);
 
 }
    // 
                      Paint message in Applet window. public void paint (java.awt.Graphics g) {
 g.drawString ("StaticApplet", 10, 20);
 }
 }
 
 // This Test class inclues a static variable.
 class Test
 {
 static double pi = 3.14;
 int m;
 
 Test ()
 {}
 
 Test (int j) {
 m = j;
 }
 }
 |   
                  |  |    Latest update: Oct. 19, 2004 |