Home : Course Map : Chapter 3 : Java :
Demo 3: Static Properties
JavaTech
Course Map
Chapter 3

Introduction
Class Definition
Data Fields
Methods
Constructors
Instantiation
  
Demo 1
  Demo 2
Static Members
  Demo 3

Value&Reference
  Demo 4
Overloading
   Demo 5
Wrappers 
  Demo 6
Autobox/Unbox
   Demo 7
Arrays
  Demo 8
Exceptions
Exercises

    Supplements
MoreAboutObjects
Creating Types

Classes,Objs&JVM

Java OOP vs C++
Garbage Collection
     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

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;
  }
}

Application version:
StaticApp.java

 

Latest update: Oct. 19, 2004

           Tech
OOP in Tech Apps
Complex Number
Histogram Class
  Demo
More Wrappers

           Physics
OOP in Physics
Particle Class
Root Finding
  Demo 1
Newton Methods
  Demo 2
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.