0% completed
Bounded type parameters allow you to restrict the types that can be used as arguments in generic classes or methods. This feature is useful when you need to work with a specific group of types that share common characteristics. For example, you might want to restrict a method to accept only objects that are instances of the Number
class or its subclasses. By using bounded type parameters, you can ensure compile-time type safety and access specific methods available to the bound type.
Upper Bounded Wildcards: Restrict the type parameter to be a specific type or its subclasses.
<T extends SomeClass>
<T extends Number>
ensures that T
is either Number
or one of its subclasses (e.g., Integer
, Double
).Lower Bounded Wildcards: Restrict the type parameter to be a specific type or its superclasses.
<? super SomeClass>
List<? super Integer>
allows the list to contain Integer
or any of its superclasses, such as Number
or Object
.public class ClassName<T extends SomeClass> { // Body of the generic class using T which is restricted to SomeClass or its subclasses. }
T
to be of type SomeClass
or any subclass of SomeClass
. This means you can safely call methods defined in SomeClass
on objects of type T
.In this example, we create a generic method sum
that accepts two parameters of a type that extends Number
. The method returns the sum as a double
. This ensures that only numeric types can be passed to the method.
Example Explanation:
<T extends Number>
restricts the generic type to Number
or its subclasses.double
and returns their sum.sum
method is called with both Integer
and Double
values.This example defines a generic class Box
that only accepts types that extend the Number
class. The class provides methods to set and get the value, and a method to calculate the square of the number.
Example Explanation:
Box<T>
is defined with the constraint <T extends Number>
, meaning it can only hold numeric types.square()
that computes the square of the value.Box
are created with Integer
and Double
types, and the square()
method computes the square accordingly.Bounded type parameters in Java allow you to restrict the types that can be used with generics, ensuring type safety and enabling access to methods of the bound type. By using upper bounds like <T extends Number>
, you can ensure that generic methods and classes work only with numeric types (or any specified type hierarchy), which helps prevent runtime errors and reduces the need for casting. The examples provided illustrate both a generic method and a generic class using bounded type parameters, demonstrating how to create flexible yet type-safe code.
.....
.....
.....