【问题标题】:Why cannot use instance of interface implementation as parameter and return type?为什么不能使用接口实现的实例作为参数和返回类型?
【发布时间】:2022-11-10 05:12:01
【问题描述】:

我想问你为什么在这种情况下使用@Override会产生错误“Method does not override method from its superclass”?为什么我不能使用实现接口的类的实例作为参数并返回由同一接口定义的方法的类型?

 public interface Request {
    //....
  }

  public interface Response {
    //....
  }

  public class MyRequest implements Request {
    //....
  }

  public class MyResponse implements Response {
    //....
  }

  public interface Order {
    Response cancel(Request request);
  }

  public class MyOrder implements Order {

    @Override
    public MyResponse cancel(MyRequest request) {
      return null;
    }

  }

【问题讨论】:

  • 返回MyResponse 可以,但只接受MyRequest 则不行:如果您将变量称为Order o = new MyOrder();,您会期望o.cancel(r) 能够处理任何Request r,不仅仅是MyRequest。但是,返回值仅为MyResponse 是可以的:它始终是Response

标签: java oop


【解决方案1】:

以下方法不起作用——但继承要求它必须这样做。

class MyOtherRequest implements Request { ... }

MyOrder myOrder = new MyOrder();
Order order = myOrder; // okay because myOrder is a subtype of Order
order.cancel(new MyOtherRequest()); // unimplemented!

因此,子类型的方法必须接受全部超类型的方法可以接受的可能值——不仅仅是一个子集。

【讨论】:

  • 我懂了。因此,当我需要在MyOrder#cancel 中指定我的MyRequest 实现的具体参数时,我需要接受Request 并稍后自己将其转换为MyRequest,对吗?
  • 理想情况下,如果您需要该方法中的某些东西,Request 将能够返回它,而不是依赖于具体类型。您试图从MyRequest 中检索无法在Request 中抽象的具体信息是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
  • 2021-10-11
相关资源
最近更新 更多