【问题标题】:Can you have a private attribute which type is an Interface? [closed]你可以有一个私有属性,它的类型是一个接口吗? [关闭]
【发布时间】:2013-12-09 02:08:49
【问题描述】:

在我们的代码中,我们应该有一个Interface(我们称之为InterfaceMap),它具有让您将单元格放入工作表中的方法(putCell()、getCell() 等)。

我们有一个名为OurSheetMatrix 的类,它实现了该接口映射。我们可以在不同的班级Sheet 上做点什么吗,比如:

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

我认为我们可以不使用接口,而是使用抽象类来做到这一点。但现在,我不确定。

【问题讨论】:

    标签: java interface private


    【解决方案1】:

    是的。 OurSheetMatrixis-aInterfaceMap。但是,您不能说new InterfaceMap();,因为您不能直接instantiate 接口(最好将它们视为承诺[或更正式的合同])。抽象类相似但不同,重要的是关系(它们不能直接实例化)。

    【讨论】:

      【解决方案2】:

      是的,你可以做到:)

      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 对象也是InterfaceMaps,但InterfaceMaps 不一定 OneSheetMatrix 对象,因此对doSomethingElse 的调用无效-可能还有其他实现InterfaceMap的类。

      【讨论】:

        猜你喜欢
        • 2022-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-11
        • 1970-01-01
        相关资源
        最近更新 更多