tags:

views:

219

answers:

8

can a static method be invoked before even a single instances of the class is constructed?

+1  A: 

Yes, because static methods cannot access instance variables, so all the JVM has to do is run the code.

DigitalRoss
thank you very much
Abhishek Sanghvi
A: 

Yes, you can access it by writing ClassName.methodName before creating any instance.

sepp2k
+8  A: 

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();
dfa
+2  A: 

Yes, that is exactly what static methods are for.

ClassName.staticMethodName();

DaveJohnston
A: 

Not only can you do that, but you should do it.

Burkhard
thank you very much
Abhishek Sanghvi
+1  A: 

Static methods are meant to be called without instantiating the class.

craftsman
+1  A: 

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 ...
    }
}
Paul Hanbury
A: 

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.

newacct