Wednesday, March 9, 2016

Java Generics Example : How To Write A Simple Generics Class

Intro


This example will demonstrates how to write a simple generics class in Java programs. In this example, we use only single parameter.

Example


package com.freesamplecode.java.generics;

public class SimpleGenericsDemo {

    public static void main(String[] args){

         // create an object GenericClassDemo with a String parameter
         GenericClassDemo<String> genericClassDemoString = new GenericClassDemo<String>("free-samplecode.blogspot.com");
         genericClassDemoString.printObjectType();

         // create an object GenericClassDemo with a Boolean parameter
         GenericClassDemo<Boolean> genericClassDemoBoolean = new GenericClassDemo<Boolean>(Boolean.TRUE);
         genericClassDemoBoolean.printObjectType();

         // create an object GenericClassDemo with a Integer parameter
         GenericClassDemo<Integer> genericClassDemoInteger = new GenericClassDemo<Integer>(Integer.MAX_VALUE);
         genericClassDemoInteger.printObjectType();

    }
}



class GenericClassDemo<T>{

     //declaring object type
     private T objectRef;

     //create a class constructor
     public GenericClassDemo(T param){
         this.objectRef = param;
     }

     public T getObjectRef(){
        return objectRef;
     }

     public void printObjectType(){
        System.out.println("Type of object is "+objectRef.getClass().getName());
    }
}


Output


Type of object is java.lang.String
Type of object is java.lang.Boolean
Type of object is java.lang.Integer

Screenshot


How To Write A Simple Generics Class


Related Posts:

0 comments: