2016-10-28 37 views
-1

我有一个Java类,看起来像这样:Java的构造与extends关键字

public class thisThing { 

    private final Class<? extends anInterface> member; 

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

我的问题是:我怎么叫thisThing构造?

+0

我可能不理解你的问题,但并不需要简单地调用新thisThing()和作为参数传递任何实现anInterface的对象? – facundop

+1

了解Java编码标准:应该是ThisThing – duffymo

+1

您只需将它传递给一个实现接口的类即可... – Li357

回答

3

为了调用thisThing你需要定义一个实现anInterface第一类的构造函数:

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

现在你可以实例thisThing如下:

thisThing theThing = new thisThing(ClassForThisThing.class); 

这样的实例背后的想法通常会给thisThing一个类,通过它可以通过反射创建anInterface的实例。编译器可以确保你传递给构造函数的类是anInterface兼容,确保蒙上这样

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

总是在运行时取得成功。

1

我不喜欢你所做的。

为什么不是这样?这里不需要泛型。你只是在做作文。通过实施AnInterface的任何参考。 Liskov替代原则说,一切都会正常工作。

public class ThisThing { 

    private AnInterface member; 

    public ThisThing(AnInterface member) { 
     this.member = member; 
    } 
} 

这里的接口:

public interface AnInterface { 
    void doSomething(); 
} 

下面是一个实现:

public class Demo implements AnInterface { 
    public void doSomething() { System.out.println("Did it"); } 
} 
+0

关键是我没有做到这一点,我坚持下去! – NWS

+0

你还没有做过什么?实现接口? – duffymo

+0

定义thisThing ...按原样提供。 – NWS