我是初学者,也是学习仿制品的新手 https://docs.oracle.com/javase/tutorial/java/generics/bounded.html
我正在学习多重边界 我所理解的是你可以指定类如下
class D <T extends A & B & C> { /* ... */ }
D<A> d = new D<>();
仅当A确实实现B和C时 其他明智的编译时错误将是偶然的 另外B和C应该是Interface其他方面//接口被编译时会发生编译错误
我不是在谈论通配符
我的问题是我没有得到任何真正的程序使用。 我正在寻找一种方法/示例,如何在编码时使用多重绑定泛型。
我什么时候应该使用它?
感谢
答案 0 :(得分:1)
请考虑以下代码段:
class SpineWarmCollection <T extends Vertebrate & Warmblooded> { /* ... */ }
class Mammal extends Vertebrate implements Warmblooded {}
class Bird extends Vertebrate implements Warmblooded {}
class Reptile extends Vertebrate {}
SpineWarmCollection<Mammal> mammalCollection = new SpineWarmCollection<>();
SpineWarmCollection<Bird> birdCollection = new SpineWarmCollection<>();
SpineWarmCollection<Reptile> reptileCollection = new SpineWarmCollection<>(); // Generates a compile error, since Reptiles are not warmblooded.
脊椎动物是动物分类学中的一类;然而,warmbloodedness是一个特点。由于哺乳动物和鸟类都是经典的,但它们没有单一的祖先类别,但它们的共同祖先脊椎动物不是。
由于T只能是扩展Vertebrate和Warmblooded的类,因此泛型可以访问在Vertebrate和Warmblooded中声明的任何方法。
你甚至不需要上课。 T只能扩展接口,这将允许实现接口的任何类集合使用泛型,即使这些类集合彼此完全无关。