Sobes.tech
Junior — Middle

Should you use extends when defining generics and in what cases is it considered good practice?

sobes.tech AI

Answer from AI

In Java, using extends when defining generics allows you to restrict the types that can be passed to the type parameter to subclasses or implementations of the specified class or interface. This is called an upper bounded wildcard.

It is good practice to use extends in the following cases:

  • When a method or class should work with objects that guaranteedly have a certain set of methods or properties (for example, all subclasses of Number).
  • To ensure type safety and prevent errors during compilation.
  • When you need to read data from a collection, and it is important that the elements are at least of a certain type.

Example:

public <T extends Number> void processNumbers(List<T> numbers) {
    for (T number : numbers) {
        System.out.println(number.doubleValue());
    }
}

Here, the method accepts a list of any objects that are subclasses of Number, allowing the use of Number methods within the method.

If you need to write into a collection, super (lower bound) is often used. Overall, extends helps make the code more flexible and safe by restricting the types you can work with.

Should you use extends when defining generics and in… - sobes.tech