使用实现中声明的接口中未定义的方法

rya*_*dlf 3 java methods interface upcasting

我有一个由接口定义的类

public interface Test {
    void testMethod();
}

Test test = new TestImpl();

public class TestImpl implements Test {
    @Override
    public void testMethod() {
         //Nothing to do here
    }

    public void anotherMethod() {
        //I am adding this method in the implementation only.
    }
}
Run Code Online (Sandbox Code Playgroud)

我该如何调用anotherMethod?

test.anotherMethod(); //Does not work.
Run Code Online (Sandbox Code Playgroud)

我希望能够在实现中定义一些方法,因为在我的生产代码中,Test接口涵盖了相当广泛的类,并由多个类实现.我使用实现中定义的方法来设置单元测试中DI框架未涵盖的依赖关系,因此方法从实现变为实现.

Ell*_*tus 6

问题出在以下几行:

Test test = new TestImpl();
Run Code Online (Sandbox Code Playgroud)

这告诉编译器忘记新对象是TestImpl并将其视为普通的旧测试.如您所知,Test没有anotherMethod().

你所做的被称为"向上转换"(将对象转换为更通用的类型).正如另一张海报所说,你可以通过不上传来解决你的问题:

TestImpl test = new TestImpl();
Run Code Online (Sandbox Code Playgroud)

如果您确定 Test对象确实是TestImpl,您可以向下转换它(告诉编译器它是一个更具体的类型):

Test test = new TestImpl();
:
((TestImpl) test).anotherMethod();
Run Code Online (Sandbox Code Playgroud)

但是,这通常是一个坏主意,因为它可能导致ClassCastException.使用编译器,而不是反对它.