can a static method be invoked before even a single instances of the class is constructed?
-
1When learning java, one of your first encounters with static concepts is the use of System.out.println(). It is an interesting bit of code, in particular System and System.out; let alone the implementations of println().Brian– Brian2009年08月29日 19:39:35 +00:00Commented Aug 29, 2009 at 19:39
9 Answers 9
absolutely, this is the purpose of static methods:
class ClassName {
public static void staticMethod() {
}
}
In order to invoke a static method you must import the class:
import ClassName;
// ...
ClassName.staticMethod();
or using static imports (Java 5 or above):
import static ClassName.staticMethod;
// ...
staticMethod();
Comments
As others have already suggested, it is definitely possible to call a static method on a class without (previously) creating an instance--this is how Singletons work. For example:
import java.util.Calendar;
public class MyClass
{
// the static method Calendar.getInstance() is used to create
// [Calendar]s--note that [Calendar]'s constructor is private
private Calendar now = Calendar.getInstance();
}
If you mean, "is it possible to automatically call a specific static method before the first object is initialized?", see below:
public class MyClass
{
// the static block is garanteed to be executed before the
// first [MyClass] object is created.
static {
MyClass.init();
}
private static void init() {
// do something ...
}
}
Comments
Yes, that is exactly what static methods are for.
ClassName.staticMethodName();
Comments
Yes, because static methods cannot access instance variables, so all the JVM has to do is run the code.
Comments
Static methods are meant to be called without instantiating the class.
Comments
Yes, you can access it by writing ClassName.methodName before creating any instance.
Comments
Not only can you do that, but you should do it.
Comments
In fact, there are a lot of "utility classes", like Math, Collections, Arrays, and System, which are classes that cannot be instantiated, but whose whole purpose is to provide static methods for people to use.
Comments
Yes, that's definitely possible. For example, consider the following example...
class test {
public static void main(String arg[]) {
System.out.println("hello");
}
}
...if then we run it, it does execute, we never created a instance of the class test. In short, the statement public static void main(String arg[]) means execute the main method without instantiating the class test.