开发者

Why is there an error in the following code? Why is the overloading not successful?

开发者 https://www.devze.com 2023-01-31 00:30 出处:网络
// signatures of the reset method at //1 and //2 after erasure will be different // then why don\'t they overload?
// signatures of the reset method at //1 and //2 after erasure will be different
// then why don't they overload?

public class Test<T>{
    public static void main(String[] args) { 
        WordBox<S开发者_开发知识库tring> city = new WordBox<String>("Skogland"); 
        city.reset("waiting");  // error: ambiguous 
    }
}


class Box <T> { 
    private T theThing; 
    public Box( T t) { theThing = t; } 
    public void reset( T t) { theThing = t; } //1  
} 

class WordBox< S extends CharSequence > extends Box< String > {
    public WordBox( S t)    { super(t.toString().toLowerCase()); }
    public void reset( S t) { super.reset(t.toString().toLowerCase()); }  //2
}


java.lang.String extends CharSequence, so calling city.reset("waiting") matches both WordBox.reset(S extends CharSequence) and Box.reset(String).

To fix the problem, you should either ensure WordBox.reset() accepts the same type as Box.reset(), in which case WordBox.reset() overrides Box.reset(), or, conversely, make sure WordBox.reset() accepts a type that does not overlap with Word.reset(), in which case WordBox.reset() overloads Box.reset(). In the example you give, I get the feeling you'd probably want WordBox.reset() to override Box.reset().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号