Tuesday, 16 May 2017

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


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:
https://sites.google.com/site/ramj2eev1/home/javabasics/GenericsMethodDemo_Bird_emp_App.zip?attredirects=0&d=1

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/539015917c8406e4be671410d713073b3971d1a5/BasicJava/GenericsMethodDemo_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