Thursday, 8 June 2017

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


Click here to watch in Youtube :
https://www.youtube.com/watch?v=iDFnRvIwzUI&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;
    }

}
GenericDemo.java 
public class GenericDemo
{
    public static void main(String[] args)
            throws IllegalAccessException, InstantiationException
    {

        Bird bird = getInstance(Bird.class);
        System.out.println(bird);

        Employee employee = getInstance(Employee.class);
        System.out.println(employee);

    }

    /*
     * Class objects can be used as type specifications too, at runtime.
     */
    public static <T> T getInstance(Class<T> theClass)
            throws IllegalAccessException, InstantiationException
    {

        return theClass.newInstance();
    }
}
Output 
Bird@58d25a40
Employee@726f3b58
Click the below link to download the code:

CLICK HERE

No comments:

Post a Comment