简体   繁体   中英

Implement Interface with Generic Java

I can't call string methods on element and argument . The UML diagram tells me that StartsWith class has a Generic Type T>String . I read in an other post you need to implement it in this way <T extends String> . I would like to substitute Object for T in the method here public boolean predicate(Object element, Object argument) but the compiler throws at me thats not possible.

interface:

public interface Intaf<T> {

    public boolean pres(T element, T argument);
}

class:

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);
    }
}

You want to implement Intaf<T> . Just saying Intaf implies Intaf<Object> .

You need to change as Intaf<T> and change the arguments as type T

@Override
public boolean pres(T element, T argument) {
 ....
}

Change to

public class StartsWith <T extends String> implements Intaf<T> {

    @Override
    public boolean pres(T element, T argument) {

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

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

        return firstLetterElement.equals(firstLetterArgument);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM