被泛型搞懵了!!

孤独的小鸟 2016-10-21 03:28:37
//这个是定义的一个泛型类:
class Test< T extends Fruit > {

}
//下面这个是public类
public class TestExtends {
public static void main(String[] args) {
Test test = new Test<Fruit>();
Test<Fruit>test = new Test();
}
}

上面这两个写法有上面区别?
Test test = new Test<Fruit>();
Test<Fruit>test = new Test();
...全文
407 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
巷子里的鸟 2016-10-24
  • 打赏
  • 举报
回复
楼主不妨把class Test< T extends Fruit > { }添加个泛型对象,变为 class Test< T extends Fruit > { T t; } 这样的话由于需要给 T t提供个具体的类型,所以Tset后必须加一个<>表面T代表的类型。 因为你class Test< T extends Fruit > { } 不带对象,没有对象需要具体化,所以Test不带<>也能通过编译。 java的泛型比较难理解, 感兴趣就去了解下类型擦除吧
解开者 2016-10-22
  • 打赏
  • 举报
回复
泛型的作用是辅助编译期类型检查,所以只有声明类型(前边的)有意义,后边的没有意义。 第一个相当于没用泛型,第二个相当于声明了参数类型为Fruit的泛型类对象。
孤独的小鸟 2016-10-21
  • 打赏
  • 举报
回复
引用 楼主 guoxiu520 的回复:
//这个是定义的一个泛型类:
class Test< T extends Fruit > {

}
//下面这个是public类
public class TestExtends {
public static void main(String[] args) {
Test test = new Test<Fruit>();
Test<Fruit>test = new Test();
}
}

上面这两个写法有上面区别?
Test test = new Test<Fruit>();
Test<Fruit>test = new Test();



原图片看这里!!!
孤独的小鸟 2016-10-21
  • 打赏
  • 举报
回复
引用 3 楼 weixin_36463152 的回复:
[quote=引用 2 楼 weixin_36463152的回复:]第一个应该无法通过编译。
第二个是用的jdk1.7的新特性。但少了符号吧
完整写法Test<fruit> test1 = newTest<>();

csdn显示不完整,就是你第二个 在new Test()后面加个尖括号[/quote]




但是,确实没有报错!
weixin_36463152 2016-10-21
  • 打赏
  • 举报
回复
引用 2 楼 weixin_36463152的回复:
第一个应该无法通过编译。 第二个是用的jdk1.7的新特性。但少了符号吧 完整写法Test<fruit> test1 = newTest<>();
csdn显示不完整,就是你第二个 在new Test()后面加个尖括号
weixin_36463152 2016-10-21
  • 打赏
  • 举报
回复
第一个应该无法通过编译。 第二个是用的jdk1.7的新特性。但少了符号吧 完整写法Test<fruit> test1 = newTest<>();
自由自在_Yu 2016-10-21
  • 打赏
  • 举报
回复
应该这样写的 Test<Fruit> test = new Test<Fruit>();

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧