Java级联继承:匿名类VS委派或内部类

问题描述

我想知道我们是否可以在Java中实现这样的目标。

我们有一个带适配器Adapter的接口Interface1,以及另一个从Interface1继承的接口,如下所示:

public interface Interface1 {
    void doSomething();
}
public interface Interface2 extends Interface1 {
    void doOtherThing();
}

public abstract class Adapter implements Interface1 {
    public void doSomething() {
        System.out.println("nope");
    }
}

然后,我们要依靠适配器以工厂方法实例化Interface2

public class SomeWhere {

    public static Interface1 create1() {
        return new Adapter () {};
    }

    public static Interface2 create2() {
        return new Adapter & Interface2 () { //  Generic formalism,but obvIoUsly it does not compile
            public void doOtherThing() {
                System.out.println("Why me?!");
            }
        };
    }

}

我的具体应用程序定义了MyObject(getters +方法)和MyObject.Editable(setters)之类的接口,MyObject中的大多数代码都可以定义为接口中的代码(但我做了一个适配器!),因为它依赖于getter方法。 ,但是我有几种实现会根据对象的性质而具有不同的getter,而其他一些实现则需要Override,但每次表示少于5行代码...

因此,我正在寻找使用匿名类而不是匿名类的解决方案 委派:

    return new Interface2 () {
        Interface1 delegate /* = new Adapter() */;
        
        public void doSomething() {
            delegate.doSomething();
        }
        public void doOtherThing() {
            System.out.println("Why me?!");
        }
        
    }

(这里有20多种方法代码将保持可读性!)

或内部类:

    class AnotherAdapter extends Adapter implements Interface2 {...}

即使与授权相比,冗长的问题也大大减少了。

我想我已经读过一些关于Java 8或更低版本的信息,也许有些技巧可以在今天完成工作(^ _ ^)'

PS:没有匿名类和内部(方法)类,我可以像这样实现它

public class SomeWhere {

    public static void main(String[] args) {
        create2().doOtherThing();
    }

    public static Interface2 create2() {
        class Adapter2 extends Adapter implements Interface2 {
            public void doOtherThing() {
                System.out.println("Why me?!");
            }
        }
        return new Adapter2();
    }

}

但这只是另一种内部类...

解决方法

为什么Adapter未实现Interface2

public abstract class Adapter implements Interface1,Interface2 {
    public void doSomething() {
        System.out.println("Nope");
    }

    // ... omitted 500 methods that are placed here to save your day
}

然后您可以使用

返回它
public class SomeWhere {

    public static Interface2 create2() {
        return new Adapter () {
    
            // Only need to provide the implementation for that single abstract method here 
            @Override
            public void doOtherThing() {
                System.out.println("Why me?!");
            }
        };
    }
}