Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use or how to use Multiple Bound in generics

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

I am learning about Multiple Bounds what I understood is you can specify class like follows

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

only if A does implements B and C both other wise compile time error will ocur also B and C should be Interface other wise //interface is expeced compile time error will occurs

I am not talking about wildcards

My problem is I am not getting any real programing use of this. I am finding a way/example how can i use Multiple bound generics while codding.

When should I use it?

thanks

like image 975
Miral Bhalani Avatar asked Oct 30 '22 18:10

Miral Bhalani


1 Answers

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, warmbloodedness is a trait. There's no single ancestor class for warmblooded-ness, since both Mammals and Birds are warmblooded, but their common ancestor, Vertebrate, is not.

Since T can only be a class that extends Vertebrate and Warmblooded, the generic can access any methods declared in Vertebrate and Warmblooded.

You don't even need a class. T could extend interfaces only, which would allow a generic to be used by any sets of classes that implement the interfaces, even of those sets of classes are completely unrelated to one another.

like image 73
Jim Humelsine Avatar answered Nov 15 '22 04:11

Jim Humelsine