如何在构造函数中实例化接口类型对象?

时间:2015-12-28 17:10:26

标签: java

考虑这个伪代码

public interface Interface {...}
public class A implements Interface{...}
public class B implements Interface{...}

现在我们得到了一个带有接口类型

字段的类Container
public class Container{
Interface field;
...}

如何创建Container的构造函数,以便在实例化字段时调用正确的构造函数,具体取决于是否将A或B的参数传递给它?

3 个答案:

答案 0 :(得分:1)

Container不会调用构造函数。无论创建Container什么,都会给它一个A或B类的实例。

e.g。

public Container createContainer() {
    final Interface myDependent = new A();
    return new Container(myDependent);
}

public class Container {
     private Interface interface;

     public Container(Interface interface) {
         this.interface = interface;
     }
     ...
}

依赖注入的一个主要思想是, don

答案 1 :(得分:0)

接口无法实例化它们。

只需创建一个采用Interface类型

的构造函数
Container(Interface in){
   this.field = in;
}

现在调用Container构造函数时会传递您喜欢的任何实现。

答案 2 :(得分:0)

  

如何创建Container的构造函数,以便在实例化字段时调用正确的构造函数,具体取决于是否将A或B的参数传递给它?

我认为你问的是课程Container的构造函数,而不是接口Interface(不能有任何)或类AB(因为你)预先假设已经提供了这些类型之一的对象作为参数)。如果参数表达式的静态类型是AB之一,您可以通过提供重载的构造函数来实现您的目标:

public Container(A interface) {
    // ...
}

public Container(B interface) {
    // ...
}

另一方面,如果您假设只知道参数实现了Interface,但是您想要根据提供的实现而不同地初始化Container,那么您应该再想想。可以做这样的事情 - 例如通过使用instanceof运算符在运行时测试提供的实现 - 但几乎任何这样的机制都是设计不良的表现,并且在实践中很可能给你带来麻烦。