Generic Class and Methods - JAVA - Java2021 : Online Tutorials Hub

Java2021 : Online Tutorials Hub

JAVA | Advance Java | MySQL | Data Structure | Git | HTML | CSS | JS

Latest

Post Top Ad

Friday, May 1, 2020

Generic Class and Methods - JAVA

How to create generics class | Syntax and Example
About Generic Classes :
  • java generics methods and generics classes enable programmers to specify,with a single method declaration,a set of related methods or,with a single class declaration,a set of related types.
  • a generics class declaration looks like a non-generics class declaration,except that the class name is followed by a type parameter section.
  • As with generics methods,the type parameter section of a generics class can have one or more types parameters separated by commas.
Let see syntax of Generic Class : 
public class MyData<T> //MyData is class name and T is any return type
{
private T t;
public void add(T t){
this.t=t;
}
public T get(){
return;
}
}

How to create Object of Generic Classes
Object creation(syntax of object) :  

MyData<Integer> i=new MyData<Integer>();

Taking two example before generic creation and after generic creation
class GenericClassExample {
    Integer i;
    public void data(Integer i1){
        i=i1;
    }
    public Integer get(){
        return (i);
    }
    public static void main(String[] args)
    {
        GenericClassExample g=new GenericClassExample();
        Integer i= new Integer(5);
        g.data(i);
        System.out.println(g.get());
    }
}
Explain : In this class two method one is data and second is get.in data method we can store one type of value that is integer and we get value through get() method.
second is main method we create object of this class and call data()method. here Integer is a non primitive data type. this is a example of before making generics class.

Generic Class Example
class GenericExplain<T>
{
    T i;
    public void display(T i1){
        i=i1;
    }
    public T get(){
        return  (i);
    }
    public static void main(String[] args) {
        GenericExplain<String> g=new GenericExplain<String>();
        GenericExplain<Integer> i=new GenericExplain<Integer>();
        i.display(95);
        g.display("ravi");
        System.out.println(i.get()+" "+g.get());
    }
}
Explain : This is example of generic class.here T is a Type of Object.here are two method one is display() and second is get() method.in this example we can store any Type of value because this is a generics class.when we create object of that class we use only Type of storing value like (Integer,String...etc) using(<Type>) as seen in example.

No comments:

Pages