You can reference a static variable via a reference to any instance of the class. : static « Modifiers « SCJP

Home
SCJP
1.Java Source And Data Type
2.Operators
3.Modifiers
4.Type Casting
5.Statements
6.Object Oriented
7.Thread
8.Utility Classes
9.File
SCJP » Modifiers » static 
3.8.8.You can reference a static variable via a reference to any instance of the class.
//(result in confusing code)

class MyClass {
  static int x = 0;

  MyClass() {
    x++;
  }
}

public class MainClass {
  public static void main(String[] argv) {
    MyClass e1 = new MyClass();
    MyClass e2 = new MyClass();
    e1.x = 100;
    e2.x = 200;

    System.out.println(e1.x);
  }
}

200




A better way to refer to a static variable is via the class name. 

class MyClass {
  static int x = 0;

  MyClass() {
    x++;
  }
}

public class MainClass {
  public static void main(String[] argv) {
    MyClass e1 = new MyClass();
    MyClass e2 = new MyClass();
    MyClass.x = 100// Why did I do this?
    MyClass.x = 200;

    System.out.println(e1.x);
  }
}

200
3.8.static
3.8.1.static variable and method
3.8.2.Declare and uses a static counter variable
3.8.3.An example of illegal access of a nonstatic variable from a static method
3.8.4.Accessing Static Methods and Variables
3.8.5.Use the dot operator on the class name, as opposed to using it on a reference to an instance
3.8.6.An example of a redefined static method
3.8.7.static features is part of a class, not individual instance of the class.
3.8.8.You can reference a static variable via a reference to any instance of the class.
3.8.9.Static methods are not allowed to use the nonstatic features of their class.
3.8.10.A static method must specify which instance of its class owns the variable or executes the method.
3.8.11.Static Initializers
3.8.12.Non-static methods may access both static and non-static variables.
3.8.13.Nested classes can be declared static, in which case they belong to the class as a whole, not any particular instance.
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.