When to use or how to use multiple bindings in generics

I am new to generics and learning generics from listening to https://docs.oracle.com/javase/tutorial/java/generics/bounded.html

I learn about multiple borders, I realized that you can specify a class as follows

class D <T extends A & B & C> { /* ... */ }
D<A> d = new D<>();

only if A implements B and C as another wise compile-time error will B and C also have to be connected to another wise interface // interface expeced compile-time error

I'm not talking about wildcards

My problem is that I am not getting any real use of this software. I find a way / example of how I can use multiple related generics during coding.

When should I use it?

thank

+4
source share
1 answer

Consider the following snippets:

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.

Vertebrate is a class in animal taxonomy; however, warm-bloodedness is a trait. There is not a single ancestral class for warm-bloodedness, since both mammals and birds are of a warm-blooded nature, but their common ancestor, vertebrate, is not.

Since T can only be a class that applies to vertebrates and warm-blooded, the general can access any methods declared in vertebrates and warm-blooded.

You don’t even need a class. T can expand only interfaces, which would allow using generic for any sets of classes that implement interfaces, even from those sets of classes that are completely unrelated to each other.

+1

Source: https://habr.com/ru/post/1657909/