0

Consider the following classes and interfaces in java.

A

public interface A{

}

B

public class B implements A{

}

C

public class C implements A{

}

Some Client

main(){
     //variable to refer to only a class which implements A interface
     Class<? implements A> clazz;// this is giving compile errors
}

Question

Class<? implements A> clazz; is giving compile errors. how do i represent a variable to hold a class which implements an interface A.

PS: i know about <? extends A> and <? super A>. But need an analogous one for interface.

stallion
  • 1,901
  • 9
  • 33
  • 52
  • 1
    Quick google search and a good answer was given here explaining there shouldn't be a difference between using the extends keyword in this case instead. [Java generics - why is "extends T" allowed but not "implements T"?](https://stackoverflow.com/questions/976441/java-generics-why-is-extends-t-allowed-but-not-implements-t) – AndrewG Dec 31 '19 at 20:30
  • 3
    It's `extends`. No difference for interface Vs class. – Andy Turner Dec 31 '19 at 20:30
  • Type mismatch: cannot convert from Class to Class extends A> – stallion Dec 31 '19 at 20:36

1 Answers1

1

I'm not sure what your intention is here but I believe you can just declare clazz as an instance of the interface.

main(){

 A clazz;
}

Then since B implements A you should be able to do something like the following with no problems

A = new B();
zreker
  • 11
  • 1