Java – Generic Class Example

[code lang=”java”]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());
}
}[/code]
Result:

Integer Value :10
String Value :Hello World

Java – Create Immutable Class Example

[code lang=”java”]// 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;
}
}[/code]
[code lang=”java”]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());
}
}[/code]