Java – Singleton Class Implementation

Following implementation shows a classic Singleton design pattern:

public class ClassicSingleton {

	private static ClassicSingleton instance = null;

	protected ClassicSingleton() {
		// Exists only to defeat instantiation.
	}

	public static ClassicSingleton getInstance() {
		if(instance == null) {
			instance = new ClassicSingleton();
		}
		return instance;
	}

}

Java – Generic Class Example

public class Box {

    private T t;

    public void add(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }

    public static void main(String[] args) {
        Box integerBox = new Box();
        Box stringBox = new Box();

        integerBox.add(new Integer(10));
        stringBox.add(new String("Hello World"));

        System.out.printf("Integer Value :%d\n\n", integerBox.get());
        System.out.printf("String Value :%s\n", stringBox.get());
    }
}

Result:

Integer Value :10
String Value :Hello World

Java – Create Immutable Class Example

// declare class as final
final class Immutable {

    // declare all variables as final
    private final int val1;
    private final String val2;

    // provide constructor to set the values
    public Immutable(int a, String s) {
        val1 = a;
	val2 = s;
    }

    // provide getters only
    public int getVal1() {
        return val1;
    }

    public String getVal2() {
        return val2;
    }
}
public class ImmutableClassDemo {
    public static void main(String[] args) {
        Immutable obj = new Immutable(10, "Immutable Class Example");
	System.out.println(obj.getVal1());
	System.out.println(obj.getVal2());
   }
}

Page 1 of 3123