编程语言
首页 > 编程语言> > Java:在同一接口的另一个默认方法中调用默认方法

Java:在同一接口的另一个默认方法中调用默认方法

作者:互联网

我对Java 8功能非常陌生,并尝试了解默认方法.有没有比使用匿名类更简单的方法来通过同一接口的另一个默认方法来调用默认方法?
例如:

public class Frame{

    public static void main(String... args){
        Frame.C c= new Frame.C();
        c.doSomething();
    }

    public interface A{
        public default void doSomething(){
            System.out.println("A");
        }
    }

    public interface B extends A {
        @Override
        public default void doSomething(){
            System.out.println("B");

            //is there an easier way to invoke that method??
            new B(){}.other();
        }
        default public void other(){
            //doSomething();
            System.out.println("other");
        }
    }

    public static class C implements B{
        @Override 
        public void other(){
            Lambda.B.super.other();
            System.out.println("C");

        }
    }

}

解决方法:

您的意图还不是很清楚,但是构造了new B(){}.other();暗示两件事:

>您不想调用替代方法的实现
>在完全不同的实例(新B(){})上调用other()的实例时,与之无关的实例显然是不可行的

这两件事意味着您应该改为使用静态方法:

public interface B extends A {
    @Override
    public default void doSomething(){
        System.out.println("B");

        otherInB();
    }
    default public void other(){
        otherInB();
    }
    static void otherInB() {
        //doSomething();
        System.out.println("other");
    }
}

由于您的原始方法名称未包含有用的信息,因此也无法为该静态方法建议一个有用的名称.

请注意,Java 9将在接口中引入对私有方法的支持,这允许将otherInB()隐藏到其他类中,甚至在必须在同一实例上使用其他方法的情况下使其变为非静态的.

如果Java 8中方法的可见性是一个问题,请考虑非多态方法的实际位置无关紧要,因此您始终可以使用伴随类:

public interface B extends A {
    @Override
    public default void doSomething(){
        System.out.println("B");

        BHelper.other();
    }
    default public void other(){
        BHelper.other();
    }
}

/* not public */ class BHelper {
    /* not public */ static void other() {
        //doSomething();
        System.out.println("other");
    }
}

如果实现需要实际的B实例,这甚至可以工作,因为您可以将其作为参数传递.

public interface B extends A {
    @Override
    public default void doSomething(){
        System.out.println("B");

        BHelper.other(this);
    }
    default public void other(){
        BHelper.other(this);
    }
}

/* not public */ class BHelper {
    /* not public */ static void other(B instance) {
        //doSomething();
        System.out.println("other");
    }
}

标签:default-method,java-8,java
来源: https://codeday.me/bug/20191027/1943430.html