Tag: upcasting

在Java 6中,向下转换的成本有多高?

有一个方法接收Collection类型的参数,它需要使用List类中的一些方法,当它与该参数一起使用时。 在速度方面上升昂贵吗? List list = (List) collection; 我还要注意,在此之后永远不会使用collection对象,只有list ,并且这将在Oracle Java 1.6上编译和运行。

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

我有一个由接口定义的类 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. } } 我该如何调用anotherMethod? test.anotherMethod(); //Does not work. 我希望能够在实现中定义一些方法,因为在我的生产代码中,Test接口涵盖了相当广泛的类,并由多个类实现。 我使用实现中定义的方法来设置unit testing中DI框架未涵盖的依赖关系,因此方法从实现变为实现。