Compilation issues with Java generics
世界只因有你
世界只因有你 2017-05-17 10:03:13
0
1
472

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>());
    }
}
世界只因有你
世界只因有你

reply all(1)
过去多啦不再A梦

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!