Name: tb29552 Date: 08/05/97
Requested by: company - Superior Electronics Group , email - ###@###.###
The correct way to invoke a static (or class method) is with the classname.
javac does not complain if you invoke a static method with an object reference,
( I have tried with the compiler in JDK for Winnt40, Solaris, Symantec Café)
Sample code:
============
public class testCounter {
private static int count =0;
public static int updateCount {
return ++count;
}
public static void main (String[] args) {
testCounter test1 = new testCounter();
testCounter.updateCount(); // the correct invocation of a
// static method
test1.updateCount(); // The wrong (?) way to invoke the
// static method
}
}
The above code compiles without any errors or warnings and runs fine.
I dont think anything major happens because of this but it leads to
poor code readability if used (which it is bound to be).
The Java Lanaguage Spec ( Section 8.4.3.2) says :
[ A method that is declared static is called a class method. A class
method is always invoked without reference to a particular object.
An attempt to reference the current object using the keyword this
or the keyword super in the body of a class method results in a
compile time error. It is a compile-time error for a static method
to be declared abstract. ]
I am not sure if this is a bug, or just an ambiguous statement in the
spec. C++ does not allow you to invoke a static method with an
instance of the class.
company - Superior Electronics Group , email - ###@###.###
======================================================================
- duplicates
-
JDK-4593045 warnings desired for almost certain errors
-
- Open
-
- relates to
-
JDK-4172989 Static method called via instance does not behave as specified
-
- Closed
-