0

Why doesn't this code compile?

public class GenericExperiment<T extends Number> {
    public void main(String[] args) {
        Number five = 5L;
        Number six = 6;
        GenericExperiment<? extends Number> experiment = new GenericExperiment<>(); //Does not compile
        //GenericExperiment<Number> experiment = new GenericExperiment<>(); //Compiles
        experiment.addStuff( five, six );
    }
    
    void addStuff( T firstNumber, T secondNumber ) {
        System.out.println( "The sum is " + firstNumber.intValue() + secondNumber.intValue() );
    }
}

If addStuff is defined as taking T, and T is defined as extending Number, why can't I pass in Number objects to it?

Jesse Barnum
  • 6,507
  • 6
  • 40
  • 69
  • 1
    in short: the type ` extends Number>` - not to be confused with `` - can be a `Double`, but neither `five` nor `six` is a `Double`; or it could be `Long` and we would not be allowed to add `six` (or a `Number`) (`T` represents any type that extends `Number`, but for one instance of `GenericExperiment` it means one fixed type (e.g. `T === Integer`); or `? extends Number` that is ONE unknown type that extends `Number`... kind of) – user16320675 May 25 '23 at 20:27
  • I didn't see that question, that is helpful, thanks – Jesse Barnum May 25 '23 at 20:38

0 Answers0