你怎么能像 Go 那样 "embed" Java class 中的接口?

How can you "embed" an interface in a Java class like in Go?

在 Go 中执行以下操作:

package main

type Interface interface {
    doSomething() error
    doAnotherThing() error
}
type MyImplementation struct {
    Interface
}

func (i *MyImplementation) doSomething() error {
    return nil
}

您可以实现接口的一些方法,其余的留给嵌入式接口。

假设我想在 Java 中做同样的事情并部分实现 20 个或更多方法的接口,但不想写出每个方法并调用我的底层接口。

我无法控制界面,因为它位于我正在使用的库中。 这在 Java 中可行吗?还是我必须写出整个界面?

创建一个抽象class,实现接口,只放一些常用的方法实现,然后创建普通的classes,扩展抽象class,剩下的具体方法实现。

像这样:

//don't touch the interface if its already there
interface Interface {
    public void  doSomething();
    public void doAnotherThing();
}

//use abstract class for common implementations
abstract class PartialClass implements Interface{
    @Override
    public void  doSomething() {
        System.out.println("doing someting in common code");
    }
    //no need to implement all the methods 
}

//create classes for specific implementations
class MyImplementation1 extends PartialClass {
    @Override
    public void doAnotherThing() {
        System.out.println("doing another thing in specific code");
    }
}

public class Test {
    
    public static void main(String[] args) throws Exception {
        Interface object = new MyImplementation1();
        object.doSomething();
        object.doAnotherThing();
    }

}

输出:

doing someting in common code
doing another thing in specific code

不,你不能在 Java 中这样做。

您只能在抽象 classes 中实现一些方法,但不能将它们用作实际实现(您不能使用 new 创建它们)。

要使用非抽象 class 作为接口,您需要写出每个方法并在每次调用中调用底层实例。