4

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.

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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)

2 Comments

But will it not limit the scope?
It depends on what you actually need. If you need to have a generic implementation go for the first option...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.