Friday, 9 June 2017

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


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:

CLICK HERE

No comments:

Post a Comment