search

Home  >  Q&A  >  body text

Compilation issues with Java generics

The source code is as follows and jumps to the prompt below. This code obviously cannot be compiled

I think one reason is

 BoundedEcho<String> stringEcho = new BoundedEcho<String>();

The String here cannot inherit Number. It is not a subclass of String? Is this correct?

Then another question is, in the last paragraph, I passed in a new BoundedEcho<Integer> object, and it belongs to BoundedEcho<T>. Why is an error reported here?

Is it correct to change BoundedEcho to public class BoundedEcho<? extends Number> {...}?

Source code here

public class BoundedEcho<T extends Number> {

    public T echo(T value) {
        return value;
    }

    public BoundedEcho<T> echo(BoundedEcho<T> value) {
        return value;
    }
}
public class BoundedEchoChamber{
    public static void main(String[] args) {
        BoundedEcho<Number> numberEcho = new BoundedEcho<Number>();
        numberEcho.echo(10);
        numberEcho.echo(10d);
        numberEcho.echo(10f);
        numberEcho.echo(10L);
    
        BoundedEcho<String> stringEcho = new BoundedEcho<String>();
        
        numberEcho.echo(new BoundedEcho<Integer>());
        numberEcho.echo(new BoundedEcho<Double>());
        numberEcho.echo(new BoundedEcho<Float>());
        numberEcho.echo(new BoundedEcho<Long>());
    }
}
世界只因有你世界只因有你2751 days ago522

reply all(1)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-17 10:05:13

    The problem lies in these two sentences

    public BoundedEcho<T> echo(BoundedEcho<T> value) {
            return value;
        }
        
    BoundedEcho<Number> numberEcho = new BoundedEcho<Number>();

    When instantiating, you declare T as Number, and subsequent calls must be BoundedEcho<Number>. The reason is that types such as BoundedEcho<Integer> and BoundedEcho<Number> are different classes, and there is no inheritance relationship.

    reply
    0
  • Cancelreply