|
|
Program: Example for singleton class using static block.
Description: |
Since static blocks will be called only once, we can use static blocks to develop singleton class. Below example shows how to
create singleton classes using static block. To create singleton class, make constructor as private, so that you cannot create object outside of
the class. Create a private static variable of same class type, so that created object will be pointed to this reference. Now create static block,
and create object inside static block. Since static block will be called only once, the object will be created only once.
|
Code: |
package com.java2novice.staticexmp;
public class MyStaticSingleton {
public static void main(String a[]){
MySingleton ms = MySingleton.getInstance();
ms.testSingleton();
}
}
class MySingleton{
private static MySingleton instance;
static{
instance = new MySingleton();
}
private MySingleton(){
System.out.println("Creating MySingleton object...");
}
public static MySingleton getInstance(){
return instance;
}
public void testSingleton(){
System.out.println("Hey.... Instance got created...");
}
}
|
|
Output: |
Creating MySingleton object...
Hey.... Instance got created...
|
|
|
|
|
List Of All Static Keyword Programs:- Example for static variables and methods.
- Example for static block.
- Example for static block vs constructor.
- Example for singleton class using static block.
|
|
|
What is servlet context?
The servlet context is an interface which helps to communicate with
other servlets. It contains information about the Web application and
container. It is kind of application environment. Using the context, a
servlet can obtain URL references to resources, and store attributes that
other servlets in the context can use.
Before you go and criticize the younger generation, just remember who raised them.
-- Unknown Author
|