Monday 15 May 2017

Java Tutorial: Generics in java [How to define a Generics class which accept user-defined class]


Click here to watch in Youtube :
https://www.youtube.com/watch?v=88Zfu_d9Dkw&list=UUhwKlOVR041tngjerWxVccw

Bird.java
public class Bird
{
    private String birdName;

    public String getBirdName()
    {
        return birdName;
    }

    public void setBirdName(String birdName)
    {
        this.birdName = birdName;
    }

}
Employee.java
public class Employee
{
    private String name;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

}
GenericFactory.java
/*
 * It is possible to generify your own Java classes. Generics is not
 * restricted to the predefined classes in the Java API's.
 * 
 * The <T> is a type token that signals that this class can have a type set
 * when instantiated.
 */
public class GenericFactory<T>
{
    
    Class<?> theClass = null;

    public GenericFactory(Class<?> theClass)
    {
        this.theClass = theClass;
    }

    public T createInstance()
            throws IllegalAccessException, InstantiationException
    {
        return (T) this.theClass.newInstance();
    }
}
GenericDemo.java
public class GenericDemo
{
    public static void main(String[] args)
            throws IllegalAccessException, InstantiationException
    {

        /*
         * It is not necessary to cast the object returned from the
         * factory.createInstance() method. The compiler can deduct the type of
         * the object from the generic type of the GenericFactory created,
         * because you specified the type inside the <>.
         */
        GenericFactory<Employee> empFactory = new GenericFactory<Employee>(Employee.class);
        Employee employee = empFactory.createInstance();
        System.out.println(employee);

        GenericFactory<Bird> birdFactory = new GenericFactory<Bird>(Bird.class);
        Bird bird = birdFactory.createInstance();
        System.out.println(bird);
    }

}
Output
Employee@1b701da1
Bird@442d9b6e

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/GenericsDemo_GenericClass_Bird_Emp_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/GenericsDemo_GenericClass_Bird_Emp_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/47d09ebb24294f7b507419345f38ec4cde27d544/BasicJava/GenericsDemo_GenericClass_Bird_Emp_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment