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?
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 static
s):
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With