Working with Upper Bounded Type Parameters in Java Generics

preview_player
Показать описание
A generic function with an upper bound in Java is a function that accepts a type parameter and restricts the acceptable types based on a specified class hierarchy. By using an upper bound, you can ensure that the function only works with types that are subclasses of a specific class or that implement a certain interface. This is useful when you want to create reusable code that operates on a specific set of related types.

In the code example above, we create a Shape interface and a Circle class that implements it. We then create a generic function calculateTotalArea that accepts a list of objects of type T, where T is a subclass or implementation of Shape (indicated by the extends keyword). This upper bound ensures that the function can only be called with types that are related to Shape. Finally, we create a list of Circle objects and call the calculateTotalArea function with this list, resulting in the calculation of the total area of all circles in the list.
Рекомендации по теме