Wednesday, October 30, 2013

Program: Write a simple generics class example.


Below example shows how to create a simple generics class. We have created SimpleGeneric class, which accepts single type parameter. Look at the generics class definition, the type parameter should be followed by class name and should contain with in <>, here T defines the type parameter. You can find comments at example itself.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.java2novice.generics;
 
public class MySimpleGenerics {
 
    public static void main(String a[]){
         
        //we are going to create SimpleGeneric object with String as type parameter
        SimpleGeneric sgs = new SimpleGeneric("JAVA2NOVICE");
        sgs.printType();
        //we are going to create SimpleGeneric object with Boolean as type parameter
        SimpleGeneric sgb = new SimpleGeneric(Boolean.TRUE);
        sgb.printType();
    }
}
 
/**
 * Here T is a type parameter, and it will be replaced with
 * actual type when the object got created.
 */
class SimpleGeneric{
     
    //declaration of object type T
    private T objReff = null;
     
    //constructor to accept type parameter T
    public SimpleGeneric(T param){
        this.objReff = param;
    }
     
    public T getObjReff(){
        return this.objReff;
    }
     
    //this method prints the holding parameter type
    public void printType(){
        System.out.println("Type: "+objReff.getClass().getName());
    }
}

Output:
Type: java.lang.String
Type: java.lang.Boolean

No comments: