Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a Generic Interface In Java

Tags:

java

generics

I am new to Java Generics. I have to implement an interface which is of generic type. The syntax is as follows:

public interface A{}

public interface B<T extends A>{
    public T methodB(T a) ;
}

Now I have to implement B so Lets say my Class is C

public class C implements B<T extends A>{}

The java compiler is not letting me use it this way. Also I do not want to use raw types. Please help.

like image 295
Neelam Avatar asked Dec 19 '22 04:12

Neelam


2 Answers

It should be

public class C<T extends A> implements B<T>

The type parameter is declared following the class name, and later can be used in the implements clause.

like image 67
Eran Avatar answered Jan 03 '23 18:01

Eran


If your implementing class is still a generic type you have to use this syntax:

public class C<T extends A> implements B<T> {}

As explained by Eran.

If C is not generic you simply need to specify the type argument for your interface:

public class C implements B<TypeExtendingA> {}

Where TypeExtendingA implements or extends A (or is A)

like image 23
davioooh Avatar answered Jan 03 '23 18:01

davioooh