2015-12-28 70 views
-1

考虑这个伪如何在构造函数中实例化接口类型化对象?

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

而现在我们得到了一类容器用接口类型的字段

public class Container{ 
Interface field; 
...} 

如何我做容器的构造函数,因此实例字段时,它调用取决于正确的构造A或B的参数是否传递给它?

+1

'field'将被设置为空,默认情况下,接口不能实例化。 – Ramanlfc

+1

你不能实例化接口的一个实例,你需要创建一个符合协议 – luk2302

+1

'B.class的实例。如果你真的有B类作为参数,newInstance()'会实例化B的一个实例。尽管如此,整体看起来有点腥意。 – pvg

回答

1

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

例如

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; 
    } 
    ... 
} 

一个依赖注入的主要观点是,类需要了解他们依赖的实现什么。

0

接口不能被实例化,它们被实现。

只是做一个构造函数Interface

Container(Interface in){ 
    this.field = in; 
} 

现在调用构造函数Container通过任何你喜欢的实现时。

0

如何使容器的构造函数在实例化字段时调用正确的构造函数,具体取决于A或B的参数是否传递给它?

我想你问的构造函数Container类,而不是接口Interface(不能有任何)或类AB(因为你预先假设这些类型之一的对象已经作为参数提供)。倘若静态类型的参数表达的是AB一个,就可以实现你简单地提供重载的构造函数是什么:

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

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

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

相关问题