Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using a static method, does the class every get instantiated?

Tags:

java

static

Say I have a static method increment:

public class StaticTest {
    private static int no = 0;

    public static void increment()
    {
        no++;
    }
}

When I call increment using the StaticTest.increment() syntax, does the class ever get instantiated? What if no object of that type exists on the heap already?

like image 814
james_dean Avatar asked May 01 '14 09:05

james_dean


1 Answers

When I call increment using the StaticTest.increment() syntax, does the class ever get instantiated?

The class, itself, is loaded (by the classloader), if it isn't already loaded. If it's already loaded, it is not loaded a second time. No instances of the class (objects of that class's type) are created, because you haven't created any.

Assuming all of the code that calls StaticTest.increment() is using the same classloader (which is normally the case), it doesn't matter how many different bits of code call that static method, just a single copy of the class is used. They all share it. E.g.:

// Some bit of code somewhere
StaticTest.increment();

// Another bit of code somewhere else
StaticTest.increment();

// A third bit of code in yet another place
StaticTest.increment();

Once all of those have run, the no private static member in StaticTest has the value 3.

What if no class of that type exists on the heap already?

Then then classloader loads it.


Contrast that code with this (no statics):

public class NonStaticTest {
    private int no = 0;

    public void increment()
    {
        no++;
    }

    public int getNo() // So we can see the results
    {
        return no;
    }
}

Now, we can't do this:

NonStaticTest.increment(); // WRONG, fails with error saying `increment` is not static

We do this instead:

NonStaticTest instance = new NonStaticTest();
instance.increment();
System.out.println(instance.getNo()); // "1"

The first time code does that, the NonStaticTest class is loaded by the classloader. Then, the new NonStaticTest() expression creates an instance of the class, which has a no member. The second time code does that, NonStaticTest has already been loaded, so it's not loaded again. Then the new NonStaticTest() expression creates a second instance of the class.

If we had three bits of code all doing the above, each of them would see "1", because no is specific to an instance of the class rather than being attached to the class itself.

like image 68
T.J. Crowder Avatar answered Oct 16 '22 00:10

T.J. Crowder