开发者

java interface input argument extends from a base class

开发者 https://www.devze.com 2023-02-03 05:40 出处:网络
I want to create an interface that allows any implementation class like this: public interface MyInterface

I want to create an interface that allows any implementation class like this:

public interface MyInterface
{

   void doSomething( <A extends MyBaseClass> arg1);
}

public class MyImpl implements MyInterface
{
  void doSomething ( SomeClassExtendsMyBaseClass arg1)
  {
    // do something
    // SomeClassExtendsMyBaseClass is a class that extends MyBaseClass
   }
}

I get a syntax error when doing the above. Can someon开发者_运维知识库e show me how to accomplish this goal?

Thanks


public interface MyInterface<A extends MyBaseClass>
{

   void doSomething(A arg1);
}

public class MyImpl implements MyInterface<SomeClassExtendsMyBaseClass>
{
  public void doSomething ( SomeClassExtendsMyBaseClass arg1)
  {
    // do something
    // SomeClassExtendsMyBaseClass is a class that extends MyBaseClass
   }
}


@salexander has the solution, but the reason you have to do this is that your derived class is trying to be more specific which you cannot do. The reason is as follows.

MyInterface mi = new MyImpl();
mi.doSomething(new MyOtherClassWhichExtendsMyBaseClass());

In the interface you said you can take ANY MyBaseClass, so you have to honour that.

In @salexander's solution the code would look like.

MyInterface<SomeClassExtendsMyBaseClass> mi = new MyImpl();
mi.doSomething(new MyOtherClassWhichExtendsMyBaseClass()); // compile error.


it should be

 <T extends MyBaseClass> void doSomething(T arg1);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号