JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

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...
<< Previous Program 

List Of All Static Keyword Programs:

  1. Example for static variables and methods.
  2. Example for static block.
  3. Example for static block vs constructor.
  4. Example for singleton class using static block.
Knowledge Centre
Prevent a method from being overridden
By specifying final keyword to the method you can avoid overriding in a subcalss. Similarlly one can use final at class level to prevent creating subclasses.
Famous Quotations
I respect faith, but doubt is what gets you an education.
-- Wilson Mizner

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.