Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Generics in Java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 193
    Comment on it

    Java Generics

    It has been observed that many programs or algorithms are same irrespective of data type they are applied to. To overcome this generics were added by JDK 5.Generics allows to define algorithms once which then can be applied to any datatype without any additional effort. Parameterized types can be referred as generics .A generic class is single class which is useful to operate on multiple types of data. Similar to generic class there can be generic method and generic interface.Generics can only work with objects not with primitive types.

    Program of Generic class:

    package com.java2novice.generics;
     
    public class FirstGenerics {
     
        public static void main(String arg[]){
             
            SimpleGeneric<String> obj = new SimpleGeneric<String>("JAVA2NOVICE");// for string datatype
            obj.printType();
            
            SimpleGeneric<Boolean> obj1 = new SimpleGeneric<Boolean>(Boolean.TRUE);// for boolean datatype
            obj1.printType();
        }
    }
     
    /**
     * Here A is a type parameter, and it will be replaced with 
     * actual type when the object got created. 
     */
    class SimpleGeneric<A>
    {
        private A objReff = null; //declaration of object type A
        public SimpleGeneric(A param) //constructor to accept type parameter A
        {
            this.objReff = param;
        }
         
        public A getObjReff()
       {
            return this.objReff;
        }
         
     
        public void printType()    //prints the holding parameter type
       {
            System.out.println("Type: "+objReff.getClass().getName());
        }
    }
    

    Output


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

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: