Use methods declared in implementation that are not defined in interface

后端 未结 6 1806
不知归路
不知归路 2020-12-18 11:56

I have a class defined by an interface

public interface Test {
    void testMethod();
}

Test test = new TestImpl();

public class TestImpl implements Test {         


        
6条回答
  •  盖世英雄少女心
    2020-12-18 12:39

    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.

提交回复
热议问题