猿问

用通用Java实现接口

我无法在element和上调用字符串方法argument。UML图告诉我StartsWith该类具有泛型类型T>String。我在另一篇文章中读到,您需要以这种方式实现它<T extends String>。我想在这里的方法中用Object代替T,public boolean predicate(Object element, Object argument)但是编译器向我抛出那是不可能的。


界面:


public interface Intaf<T> {


    public boolean pres(T element, T argument);

}

班级:


public class StartsWith <T extends String> implements Intaf {


    @Override

    public boolean pres(Object element, Object argument) {


        String firstLetterElement = element.substring(0,1);


        String firstLetterArgument = argument.substring(0,1);


        return firstLetterElement.equals(firstLetterArgument);

    }

}


慕森卡
浏览 186回答 3
3回答

慕盖茨4494581

改成public class StartsWith <T extends String> implements Intaf<T> {&nbsp; &nbsp; @Override&nbsp; &nbsp; public boolean pres(T element, T argument) {&nbsp; &nbsp; &nbsp; &nbsp; String firstLetterElement = element.substring(0,1);&nbsp; &nbsp; &nbsp; &nbsp; String firstLetterArgument = argument.substring(0,1);&nbsp; &nbsp; &nbsp; &nbsp; return firstLetterElement.equals(firstLetterArgument);&nbsp; &nbsp; }}

FFIVE

您要实现Intaf<T>。只是说Intaf暗示Intaf<Object>。

慕桂英3389331

您需要将asIntaf<T>更改并将参数更改为T类型@Overridepublic boolean pres(T element, T argument) {&nbsp;....}
随时随地看视频慕课网APP

相关分类

Java
我要回答