java有界類型參數(shù)的實(shí)例用法
1、為了聲明一個(gè)有界類型參數(shù),列出類型參數(shù)的名稱,然后是extends關(guān)鍵字,最后是它的上界。
public class Box<T> { private T t; public void set(T t) {this.t = t; } public T get() {return t; } public <U extends Number> void inspect(U u){System.out.println('T: ' + t.getClass().getName());System.out.println('U: ' + u.getClass().getName()); } public static void main(String[] args) {Box<Integer> integerBox = new Box<Integer>();integerBox.set(new Integer(10));integerBox.inspect('some text'); // error: this is still String! }}
2、通過(guò)修改泛型方法包含這個(gè)有界類型參數(shù)。由于我們?cè)谡{(diào)用inspect時(shí)還使用了String,因此編譯將失敗
Box.java:21: <U>inspect(U) in Box<java.lang.Integer> cannot be applied to (java.lang.String)integerBox.inspect('10'); ^1 error
3、除對(duì)可用于實(shí)例化泛型類型的類型進(jìn)行限制外,還允許調(diào)用在邊界中定義的方法。
public class NaturalNumber<T extends Integer> { private T n; public NaturalNumber(T n) { this.n = n; } public boolean isEven() { return **n.intValue()** % 2 == 0; } // ...}
知識(shí)點(diǎn)擴(kuò)展:
當(dāng)我們希望對(duì)泛型的類型參數(shù)的類型進(jìn)行限制的時(shí)候(好拗口), 我們就應(yīng)該使用有界類型參數(shù)(Bounded Type Parameters). 有界類型參數(shù)使用extends關(guān)鍵字后面接上邊界類型來(lái)表示, 注意: 這里雖然用的是extends關(guān)鍵字, 卻不僅限于繼承了父類E的子類, 也可以代指顯現(xiàn)了接口E的類. 仍以Box類為例:
public class Box<T> { private T obj; public Box() {} public T getObj() {return obj; } public void setObj(T obj) {this.obj = obj; } public Box(T obj) {super();this.obj = obj; } public <Q extends Number> void inspect(Q q) {System.out.println(obj.getClass().getName());System.out.println(q.getClass().getName()); }}
我加入了public <Q extends Number> void inspect(Q q){...}方法, 該方法的泛型只能是Number的子類.
Box<String> b = new Box<>(); b.setObj('Hello'); b.inspect(12); b.inspect(1.5); // b.inspect(true); // 編譯出錯(cuò)
到此這篇關(guān)于java有界類型參數(shù)的使用的文章就介紹到這了,更多相關(guān)java有界類型參數(shù)的使用內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向2. .NET SkiaSharp 生成二維碼驗(yàn)證碼及指定區(qū)域截取方法實(shí)現(xiàn)3. MyBatis JdbcType 與Oracle、MySql數(shù)據(jù)類型對(duì)應(yīng)關(guān)系說(shuō)明4. jsp網(wǎng)頁(yè)實(shí)現(xiàn)貪吃蛇小游戲5. CentOS郵件服務(wù)器搭建系列—— POP / IMAP 服務(wù)器的構(gòu)建( Dovecot )6. idea自定義快捷鍵的方法步驟7. ASP中if語(yǔ)句、select 、while循環(huán)的使用方法8. IntelliJ IDEA設(shè)置背景圖片的方法步驟9. django創(chuàng)建css文件夾的具體方法10. css代碼優(yōu)化的12個(gè)技巧
