你有一个私有属性,哪个类型是一个接口?

时间:2013-11-24 12:45:03

标签: java interface private

在我们的代码中,我们应该有Interface(让我们称之为InterfaceMap),它具有允许您将单元格放入Sheet(putCell(),getCell()等的方法) )。

我们有一个名为OurSheetMatrix的类来实现InterfaceMap。我们可以在不同的类Sheet上拥有某些内容,例如:

public class Sheet {
  private InterfaceMap m = new OurSheetMatrix();
  ...
}

我认为我们可能不能使用Interfaces,而是使用抽象类。但现在,我不确定。

2 个答案:

答案 0 :(得分:1)

是。 OurSheetMatrix is-a InterfaceMap。但是你不能说new InterfaceMap();,因为你不能直接instantiate一个界面(最好把它们视为承诺[或更正式的合同])。抽象类是相似但不同的,它是重要的关系(并且它们不能直接实例化)。

答案 1 :(得分:1)

是的,你可以这样做:)

private InterfaceMap m = new OurSheetMatrix();

没关系。您还可以在方法中传递对您的界面的引用:

public void doSomething(InterfaceMap iamp) {
  //Do something with an InterfaceMap. 
  //I don't know (or care) exactly what class it is, 
  //so long as it implements InterfaceMap
}

但如果你有更具体的东西:

public void doSomethingElse(OurSheetMatrix matrix) {}

不能这样调用:

InterfaceMap imap = new OurSheetMatrix();  //this is OK
doSomethingElse(imap);                     //But this? NO! can't do this!

以上对doSomethingElse的调用无法编译,因为doSomethingElse需要OurSheetMatrix。虽然我们知道它真的是OurSheetMatrix,但该方法并不知道。

所有OneSheetMatrix个对象也是InterfaceMap个,但InterfaceMap s 不一定是 OneSheetMatrix个对象,因此调用{{1无效 - 可能有其他类实现doSomethingElse

相关问题