Use methods declared in implementation that are not defined in interface

后端 未结 6 1807
不知归路
不知归路 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

    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.

提交回复
热议问题