Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a non-generic class implement a generic interface?

I've been reading "Java. A Beginner's Guide" by Herbert Schildt. In the section on generic interfaces on one page the author writes (emphasis mine):

Any class that implements a generic interface must itself be generic.

And on the next page (emphasis mine):

In general, if a class implements a generic interface, then that class must also be generic, at least to the extent that it takes a type parameter that is passed to the interface.

So are there any specific situations where a non-generic class can implement a generic interface in Java? Or all such classes are generic in that they 'inherit' that generality from the generic interface?

UPD: I should have read the section further. The author goes on to state:

Of course, if a class implements a specific type of generic interface, such as shown here: class MyClass implements Containment<Double> { then the implementing class does not need to be generic.

This is, I believe, the gist of all the answers to my post.

like image 807
John Allison Avatar asked Apr 12 '26 14:04

John Allison


2 Answers

It is possible to create a non-generic class that implements a generic interface, provided that the type parameters are provided.

A relatively simplistic example:

public class LocalDateParser implements Function<String, LocalDate> {
    public LocalDate apply (String s) {
        return LocalDate.parse(s);
    }
}

Of course, you can only assign an instance of this class to Function<String, LocalDate>, and not to any other Function<T, R>.

like image 118
Joe C Avatar answered Apr 15 '26 04:04

Joe C


I think the author is plain wrong in both statements. A generic class is a class that accepts a generic type parameter. And you can create a class that doesn't accept any generic type parameter that implements a generic interface:

public class CaseInsensitiveComparator implements Comparator<String> {

    @Override
    public int compare(String s1, String s2) {
        return s1.compareToIgnoreCase(s2);
    }
}

In fact, this class already exists in the JDK, though it's implemented differently. Please see String.CASE_INSENSITIVE_ORDER for further details.

like image 43
fps Avatar answered Apr 15 '26 03:04

fps



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!