NWS NWS - 1 year ago 131
Java Question

Java Constructor with extends keyword

I have a java Class that looks like this:

public class thisThing {

private final Class<? extends anInterface> member;

public thisThing(Class<? extends anInterface> member) {
this.member = member;

My Question is: How do I call the

Answer Source

In order to call the constructor of thisThing you need to define a class that implements anInterface first:

class ClassForThisThing implements anInterface {
    ... // interface methods go here

Now you can instantiate thisThing as follows:

thisThing theThing = new thisThing(ClassForThisThing.class);

The idea behind such instantiations is usually giving thisThing a class from which it could create instances of anInterface through reflection. Compiler makes sure that the class that you pass to the constructor is compatible with anInterface, ensuring that casts like this

anInterface memberInstance = (anInterface)member.newInstance();

would always succeed at run-time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download