简体   繁体   中英

Generics in Java — implementing interfaces

I have an interface with prototype

public interface genericInterface <E extends Comparable <E>>{}

and now I want to implement this inerface in my class, what I should wirte in class definition? The following line is giving me an error (I have implemented all the methods in the interface)

public class MyClass<Integer> implements genericInterface**<Integer Comparable<Integer>>**{ }

Syntax...

genericInterface<Integer Comparable<Integer>> -- error

genericInterface<Integer> -- error

what I should write in place of <Integer Comparable<Integer>> to make it compatible?

The class declaration should just be:

class MyClass implements genericInterface<Integer>

Generic parameters after the class name are for parameters of that class, not of classes that it is implementing.

So, for example:

interface genericInterface<E extends Comparable <E>> {
    E getKey();
}
class MyClass<T> implements genericInterface<Integer> {
    T getValue();
}

MyClass<String> m = new MyClass<String>();
Integer a = m.getKey(); // Because MyClass always has E = Integer
String b = m.getValue(); // Because m has T = String

genericInterface<Integer> g = new MyClass<Boolean>();
Integer c = g.getKey();

You can also do:

class MyClass<E extends Comparable <E>> implements genericInterface<E>

Then you can have instances of MyClass parameterized with any type that would work for genericInterface .

Generics are available in Java only since version 1.5. You should use raw types.

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