- Apache Spark 2.x for Java Developers
- Sourav Gulati Sumit Kumar
- 176字
- 2021-07-02 19:01:55
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.
推薦閱讀
- Cocos2d Cross-Platform Game Development Cookbook(Second Edition)
- TypeScript Essentials
- JIRA 7 Administration Cookbook(Second Edition)
- Vue.js 3.x從入門到精通(視頻教學(xué)版)
- 跟小海龜學(xué)Python
- Oracle 18c 必須掌握的新特性:管理與實(shí)戰(zhàn)
- Arduino家居安全系統(tǒng)構(gòu)建實(shí)戰(zhàn)
- 好好學(xué)Java:從零基礎(chǔ)到項(xiàng)目實(shí)戰(zhàn)
- JBoss:Developer's Guide
- Java程序設(shè)計(jì)教程
- 開發(fā)者測(cè)試
- Real-time Web Application Development using Vert.x 2.0
- Java EE 7 First Look
- 智能優(yōu)化算法與MATLAB編程實(shí)踐
- IBM Cognos 10 Report Studio Cookbook(Second Edition)