Here, I was trying to implement a singleton class for my Database connectivity using the inner static helper class :
package com.myapp.modellayer;
public class DatabaseConnection {
private DatabaseConnection() {
//JDBC code...
}
private static class ConnectionHelper {
// Instantiating the outer class
private static final DatabaseConnection INSTANCE = new DatabaseConnection();
}
public static DatabaseConnection getInstance() {
return ConnectionHelper.INSTANCE;
}
}
However, my doubt is when does this static inner class, ConnectionHelper, gets loaded in to the JVM memory:
At time when DatabaseConnection class gets loaded, or At a time when getInstance() method is called ?
Also, because an inner class is associated with an instance, it cannot define any static members itself. Objects that are instances of an inner class exist within an instance of the outer class.
A non-static nested class has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.
A nested class could be nonstatic or static and in each case is a class defined within another class. A nested class should exist only to serve is enclosing class, if a nested class is useful by other classes (not only the enclosing), should be declared as a top level class.
In Java a static nested class is essentially a normal class that has just been nested inside another class. Being static, a static nested class can only access instance variables of the enclosing class via a reference to an instance of the enclosing class.
When the class gets loaded is just an implementation detail; you want to know when the class is initialized. It will get initialized only when it is first needed, and that is when you call getInstance()
.
You are BTW using the lazy initialization holder class idiom which is based on exactly this guarantee by the Java Language Specification. As Josh Bloch said,
This idiom is almost magical. There's synchronization going on, but it's invisible. The Java Runtime Environment does it for you, behind the scenes. And many VMs actually patch the code to eliminate the synchronization once it's no longer necessary, so this idiom is extremely fast.
The oracle doc page says:
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
You it is loaded the same way other classes are loaded.
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