Mir*_*ani 5 java generics multiple-bounds
我是泛型新手,并且从听说 https://docs.oracle.com/javase/tutorial/java/generics/bounded.html学习泛型
我正在学习多重界限,我的理解是你可以指定类如下
class D <T extends A & B & C> { /* ... */ }
D<A> d = new D<>();
Run Code Online (Sandbox Code Playgroud)
仅当 A 实现 B 和 C 时才会发生编译时错误,B 和 C 也应该是接口,否则会发生编译时错误
我不是在谈论通配符
我的问题是我没有得到任何真正的编程用途。我正在寻找一种方法/示例,如何在编码时使用多个绑定泛型。
我应该什么时候使用它?
谢谢
考虑以下片段:
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.
Run Code Online (Sandbox Code Playgroud)
脊椎动物是动物分类学中的一类;然而,温血是一种特质。温血动物没有单一的祖先类,因为哺乳动物和鸟类都是温血动物,但它们的共同祖先脊椎动物却不是。
由于 T 只能是扩展 Vertebrate 和 Warmblooded 的类,因此泛型可以访问 Vertebrate 和 Warmblooded 中声明的任何方法。
你甚至不需要上课。T 只能扩展接口,这将允许实现接口的任何类集使用泛型,即使这些类集彼此完全无关。