| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
XyzWs Java FAQ:
How many ways can I access static members in a class?
Printer-friendly version |
Mail this to a friend
|
Advertisement
|
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 It's best practice to always invoke static member using the class name rather then an object reference of the class. |