Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  

FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement

XyzWs Java FAQ:
How many ways can I access static members in a class?


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Advertisement
XyzWs Java FAQ: How many ways can I access static members in a class?

How many ways can I access static members in a class?

A static member (static method or static variable) can be accessed by using the dot operator on the class name (e.g., Math.max(..);). This is a standard and right way to access a static member in a class.

But Java language also allows you to use an object reference to access a static member. This is bad or at least poor form because it creates the impression that some instance variables in the object are used, but this isn't the case. For example,


//Access static member from within the same class
class MyObject1 {
  static int staticVariable = 10;
  void m() {
    MyObject1 o = null;
    int i1 = staticVariable;
    int i2 = this.staticVariable;
    int i3 = MyObject1.staticVariable;
    int i4 = o.staticVariable;
  }
}

//Access static member from outside the class
class MyObject2 {
  void m() {
    MyObject1 o = new MyObject1();
    int i5 = MyObject1.staticVariable;
    int i6 = o.staticVariable;    	
  }

}

When we access a static member on an object reference, what the value of the object reference is (point to an instance or null). Only the type of the object reference matters. That is why int i4 = o.staticVariable; will not throw a NullPointerException.

It's best practice to always invoke static member using the class name rather then an object reference of the class.


Previous Next vertical dots separating previous/next from contents/index/pdf Contents

Support  | Feedback  | Help