為什么有的學(xué)生對象定義了<String>泛型,還可以傳入123int類型,有的學(xué)生對象定義了<Integer>泛型還可以傳入float、String類型,(代碼中的show3()方法) ????????????求大神解答。package com.vdate.day18;/**?* 泛型定意在方法上?*??* 泛型是個類,只能接受引用類型,不能傳int這些基本數(shù)據(jù)類型,但是可以傳他的包裝類,integer?*?*/public class demo3 { public static void main(String[] args) { Student2<String> s1 = new Student2<String>(); s1.show("hhhh"); ? ?//s1.show(123);// Student2<Integer> s2 = new Student2<Integer>(); // s2.show("hhhh"); s2.show(123);// s2.show2("dsda"); s2.show2(123F); Student2<Integer> s3 = new Student2<Integer>(); s2.show3("dsda"); s2.show3(123F); s2.show3(123); }}class Student2<E>{ int age; //泛型定義在方法上 public void show(E e) { System.out.println("show=" + e); } public void show2(Object o) { System.out.println("show=" + o); } //定義在方法上 public <A> void show3(A a) { System.out.println("show=" + a); } }
1 回答

堇延未七
TA貢獻(xiàn)36條經(jīng)驗(yàn) 獲得超19個贊
首先看show2方法,它的入?yún)⑹且粋€Object的對象,萬物都是Object的對象,所以不管傳進(jìn)來的是字符串還是整數(shù),都會轉(zhuǎn)化為Object對象輸出;show3方法中入?yún)⑹茿類型,和泛型E是沒有關(guān)系的,可以傳入任意類型
添加回答
舉報(bào)
0/150
提交
取消