Home > Software design >  Why cannot use instance of interface implementation as parameter and return type?
Why cannot use instance of interface implementation as parameter and return type?

Time:10-29

I would like to ask you why usage @Override in this case produces an error "Method does not override method from its superclass"? Why I cannot use instance of the class implemented an interface as a parameter and return type of the metod defined by same interface?

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

  }

CodePudding user response:

The following would not work -- but inheritance requires it must.

class MyOtherRequest implements Request { ... }

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

As a result, a subtype's method must accept all the possible values the supertype's method would accept -- not just a subset.

CodePudding user response:

The problem is with the parameter to cancel.

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

You can't pass a supertype to a subtype (In this case Request object to MyRequest parameter) as the implementation of the subType may have other methods that the superType interface is unaware of.

  • Related