Use methods declared in implementation that are not defined in interface

只谈情不闲聊 提交于 2019-11-29 08:04:42

The problem is with the following line:

Test test = new TestImpl();

This tells the compiler to forget that the new object is a TestImpl and treat it as a plain old Test. As you know, Test does not have anotherMethod().

What you did is called "upcasting" (casting an object to a more general type). As another poster has said, you can fix your problem by not upcasting:

TestImpl test = new TestImpl();

If you're sure that a Test object is really a TestImpl, you can downcast it (tell the compiler it is a more specific type):

Test test = new TestImpl();
:
((TestImpl) test).anotherMethod();

This is generally a bad idea, however, since it can cause ClassCastException. Work with the compiler, not against it.

use

TestImpl test = new TestImpl();

then

test.anotherMethod();//It will work now

I think through your Interface reference it is impossible to call any method which is not defined in that interface.

If you want to avoid casting directly to your implementation class, I would create another interface:

public interface SpecificTest extends Test { 
    void anotherMethod();
}

And then have your TestImpl implement that interface (which means you can declare it as either Test or SpecificTest ):

SpecificTest test = new TestImpl();
test.anotherMethod();

Of course you can access your methods as was answered above, but you should adhere to best practices in programming. So you if you can't add required methods to Interface1 create Interface2 that extends Inteface1 and finally add your methods.

You can call it if you cast to the implementing class, the one that implements that method In short:

Test test = new TestImpl();

// ... and later / somewhere else

((TestImpl) test).anotherMethod();

If you do not want to type cast it to the concrete class then you could make anotherMethod() as private method and call it inside testMethod() based on some logic.

for eg.

testMethod()
{
   if(foo)
  {
     anotherMethod();
  }
}

This is a workaround that you can use if you do not want to create new methods in child class , since you cannot call them using a parent class/interface reference.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!