Use methods declared in implementation that are not defined in interface

后端 未结 6 1791
不知归路
不知归路 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条回答
  •  -上瘾入骨i
    2020-12-18 12:32

    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();
    

提交回复
热议问题