Sunday, January 29, 2012

JAVA - Generics

With generics, we can create classes, interfaces, and methods that will work in a type-safer manner with various kinds of data.

If you define an algorithm once, independently of any specific type of data, and then apply that algorithm to a wide variety of data types without any additional effort.

Simple example:

class Type<G> {

G obj;

Type(G o) {
  obj = o;

G getType() {
  return obj;

void displayType() {
 System.out.println("Type of G is " + obj.getClass().getName());


class Demo {
   public static void main(String args[]) {
  Type<Integer> intType = new Type<Integer>(100);
  System.out.println("Integer type "+intType.getType());
  Type<String> stringType = new Type<String>("Generics");
  System.out.println("string type "+intType.getType());

No comments:

Post a Comment