Java Tutorial
IntroductionEnvironment SetupIDEBuild ManagementLanguage SpecificationBasic ProgramVariablesData TypesPackagesModifiersConditionalsLoopsObject OrientedClassesSuperInterfacesEnumStatic importInheritanceAbstractionEncapsulationPolymorphismBoxing & UnboxingConversion Formatting numbers Arrays Command line arguments in java Variable Number of arguments in Java Exception handling in Java String handling in Java StringBuffer and StringBuilder in Java Mathematical Operations in Java Date and Time in Java Regular expressions in Java Input output programming in Java File Handling Nested Classes Collections Generics Serialization Socket programming Multi-Threading Annotations Lambda Expressions Reflections in Java Singleton class in Java Runtime Class in JavaHow to load resource in JavaHow to load properties file in JavaAdvanced
Log4j – Logging framework in JavaInterview Questions in JavaSingleton Class in Java
Singleton is a class wherein we can create just a single object of that class. Runtime is one of the most important built-in Singleton class in Java library. But we can also create our custom singleton class as shown in below example. Note that we can create only one instance of that class.
package singleton;
import org.junit.Test;
/**
* Created by ssalunke on 13/04/2016.
*/
public class TestSingleTon {
@Test
public void test(){
System.out.println(SingleTon.getInstance().hashCode());
//Below statement will throw compile time error
//Runtime r = new Runtime();
//Below statement will throw compile time error
//SingleTon s1 = new SingleTon();
}
}
class SingleTon {
private static SingleTon instance = null;
private SingleTon() {
// This constructor is private which means that
//we can not create objects using new Operator
}
public static SingleTon getInstance() {
if (instance == null) {
instance = new SingleTon();
}
return instance;
}
}
Web development and Automation testing
solutions delivered!!