How do I get Static Constructor functionality in JAVA?
I am learning C # and JAVA. I found Static Constructor
in C # which is used to initialize any static data or to perform a specific action that only needs to be done once. It is called automatically before the first instance is created or any static members are referenced.
Example:
class SimpleClass
{
// Static variable that must be initialized at run time.
static readonly long baseline;
// Static constructor is called at most one time, before any
// instance constructor is invoked or member is accessed.
static SimpleClass()
{
baseline = DateTime.Now.Ticks;
}
}
My question is, how can I get the same functionality in JAVA, is there a way?
+3
source to share
2 answers
You can use a static initialization block like this:
class SimpleClass
{
static{
}
}
A static block is fetched only once, no matter how many objects of that type are created.
You can see this link for more details.
Update: The static
initialization block is only called when the class is loaded into memory.
+4
source to share