官术网_书友最值得收藏!

Creating your own generic type

In this section, we will create a class with generic type T. Classes will consist of the variable of type T and will also have a general purpose method that will return the variable of type T:

public class MyGeneric<T> {   
  T input; 
  public MyGeneric(T input) { 
    this.input=input;         
  } 
  public T getInput() 
  { 
    return input; 
  } 
} 

As described previously, MyGeneric is the class. It consists of the variable input of type T, a constructor to construct the object of the MyGenric class and initialize the variable input and a method that returns the value of T.

Now, let's implement it:

public class MyGenericsDemo { 

  public static void main(String[] args) { 
    MyGeneric<Integer> m1 =new MyGeneric<Integer>(1); 
    System.out.println(m1.getInput()); 
    //It will print '1' 
    MyGeneric<String> m2 =new MyGeneric<String>("hello"); 
    System.out.println(m2.getInput()); 
    //It will print 'hello' 
  } 
} 
 

Here, we have created two objects of the MyGeneric class, one with an integer type and the other with a string type. When we invoke the getInput method on both objects, they will return the value of their respective type.

主站蜘蛛池模板: 邵东县| 白水县| 秦皇岛市| 库尔勒市| 平原县| 扬中市| 罗源县| 青浦区| 甘德县| 韶山市| 陇西县| 五大连池市| 岗巴县| 平度市| 休宁县| 肇庆市| 含山县| 准格尔旗| 云和县| 长武县| 天峻县| 长白| 贵阳市| 桃园县| 福鼎市| 驻马店市| 旬邑县| 兴山县| 都昌县| 铜梁县| 始兴县| 石家庄市| 庆城县| 沈丘县| 中牟县| 抚松县| 旅游| 耿马| 双柏县| 青川县| 江山市|