接口参数类型的继承

时间:2012-08-16 18:56:35

标签: java

我试图将请求的基本实现作为接口函数的参数类型。

然后让各种类扩展基本请求类,为请求对象赋予更具体的含义。

但是Java需要确切的类作为参数,并且不支持由该基类扩展的类。

public interface MyInterface{
   public String getValue(BaseRequest req);
}

public class MyInterfaceImpl implements MyInterface{
   public String getValue(SpecificRequest req){ //Java will give a compile error here.
      //Impl
   }
}

public interface BaseRequest{
   int requiredA;
   int requiredB;
   //setter and getters for A and B
}

public class SpecificRequest extends BaseRequest{
   int specificValC;
   //setter and getters for C
}

实现这种模式的最佳方法是什么?或者我的设计有点太多了?

3 个答案:

答案 0 :(得分:10)

你可以使用泛型来实现类似的东西。

public interface MyInterface<R extends BaseRequest> {
   public String getValue(R req);
}

public class MyInterfaceImpl implements MyInterface<SpecificRequest> {
   public String getValue(SpecificRequest req){ 
      //Impl
   }
}

答案 1 :(得分:0)

好吧,如果你宣布你的接口为接受BaseRequest java的接口,那么java就不会让它缩小到只有SpecificRequest,这些都是OOP的基础知识。 如果您真的需要这个界面,您应该向我们展示您将要创建的界面的其他实现的示例。我的意思是很难看出你的设计的重点是告诉你是否做得太多了。

答案 2 :(得分:0)

当您实现接口时,编译器会确保您的实现对声明是真的,即您不能将参数类型缩小到派生类。

但是,您可以传入派生类:

   public class MyInterfaceImpl implements MyInterface {
       public String getValue(BaseRequest req){ 
           // ...
       }
   }

   ... 
   // calling your method
   MyInterface provider = ...
   SpecificRequest request = ...
   provider.getValue(request); 
相关问题