I would like to know if you have a class with only static methods in it, does an actual instance of the class get created somewhere when you call 1st static method?
This is somewhat confusing to understand in terms of memory management as you never actually call the constructor or create an instance of the method explicitly.
If an instance does get created, I would like to better understand where this instance lives and for how long.
No. Calling a static
method does not require (or create) an instance of a class
. See also JLS-8.4.3.2 static
methods which says (in part)
A method that is declared static
is called a class method.
...
A class method is always invoked without reference to a particular object.
Say you have
static class Foo
{
static Bar bar = new Bar();
static int func(){ ... }
}
obviously, a Foo
object will not be created for calling func()
.
However, the class Foo
needs to be loaded in memory; and to the application, there is an object corresponding to the class, which can be referred to as Foo.class
, or Class.forName("Foo")
.
A loaded class is not initialized yet. When you call a static method for the 1st time, the class is initialized; some "space" is allocated for static variables, and static initializer code (like new Bar()
) is executed.
This "space" is not visible to application as an object; but it's an in memory data structure too that concerns garbage collections (and other objects it refers to, like bar
)
The class, and the "space", are only eligible for GC when the classloader that loaded the class is eligible for GC. For usual command line applications, that never happens. But for a lot of other applications, class GC is important, and class loading needs to be carefully done.
static
methods belong to the class, not to the object reference. You can call static
method and forget about wasting memory on creating an object reference of the class being used, that doesn't happen. When you call an static
method on an object reference, you get a compiler warning on the subject. You can even call static
methods on a variable of the desired class and this variable can be null
, the static
method will be invoked with no problem.
public class Foo {
public static void sayHello(String name) {
System.out.println("Hello " + name);
}
}
//works, no instance of Foo was created
Foo.sayHello("AlexVPerl");
Foo foo = new Foo();
//works, compiler raises a warning here
foo.sayHello("AlexVPerl");
foo = null;
//works, compiler raises a warning here
//and as you can see, it doesn't matter if the instance is null
foo.sayHello("AlexVPerl");