Inferred type ‘s’ for type parameter ‘s’ is not within its bound; should extend

The error message “inferred type ‘s’ for type parameter ‘s’ is not within its bound;
should extend” typically occurs when a type parameter is not constrained to a specific type,
but the inferred type does not match the expected constraint. To fix this error, you need to
specify the correct constraint for the type parameter.

Let’s consider an example to better understand this error.

    
      class Example {
        private T value;

        public Example(T value) {
          this.value = value;
        }

        public void printValue() {
          System.out.println(value);
        }
      }

      public class Main {
        public static void main(String[] args) {
          Example example = new Example<>("Hello"); // Error: String does not extend Number
          example.printValue();
        }
      }
    
  

In the above example, we have a generic class Example that takes a type parameter
T, which is expected to be a subclass of Number. However, in the
main method, we instantiate the Example class with String
as the type argument. Since String does not extend Number, the
compiler throws an error.

To fix this error, you need to ensure that the type argument for the Example class
adheres to the constraint. In this case, you should use a type that extends Number,
such as Integer or Double.

    
      public class Main {
        public static void main(String[] args) {
          Example example = new Example<>(42); // No error
          example.printValue(); // Output: 42
        }
      }
    
  

In the modified example, we instantiate the Example class with Integer
as the type argument, which extends Number. Now, there is no error and the value
42 is printed successfully.

Similar post

Leave a comment