Skip to content
Advertisement

Generic class that implements a particular interface

So lets take this example that I have a class A and class B both A and B are implementing a specific interface letters. Now I need to make a specific function in another class wherein I need to pass either A class object or B class object and similarly do some operation on these objects and return either A or B class objects. Now I can define the function using a generic type T but the catch is T must always implement interface letters. So a Object of class 1 which doesn’t implement interface letters wont be allowed to pass this function.

public class A implements letters{...}
public class B implements letters{...}
public class LetterOperations{
 public T letterOp(T letter){..}
}

Here letterOp() must be accepting only those kind of generic classes T which implement interface letters.

Advertisement

Answer

Add type parameter bound when declaring generic class:

   public class LetterOperations<T extends letter> {
     public T letterOp(T letter){..}
   }

Or use method with type parameter:

   public <T extends letter> T letterOp(T letter){..}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement