【问题标题】:How can you "embed" an interface in a Java class like in Go?如何像 Go 一样将接口“嵌入”到 Java 类中?
【发布时间】:2021-06-23 23:34:48
【问题描述】:

在 Go 中,您可以执行以下操作:

package main

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

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

你可以实现接口的一些方法,剩下的留给嵌入式接口。

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

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

【问题讨论】:

  • 在 Java 中尝试抽象类
  • 我无法控制接口,因为它在库中,抽象类方法仍然有效吗?如果有,怎么做?

标签: java oop interface


【解决方案1】:

不,你不能在 Java 中做到这一点。

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

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

【讨论】:

    【解决方案2】:

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

    类似这样的:

    //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
    

    【讨论】:

    • 正如我所提到的,我想部分实现一个具有 20 个或更多方法的接口,所以我不想把它们全部写出来,因为我只想覆盖一些。你刚刚实现了这对我没有帮助。如果您可以展示如何只实现一个,但它仍然可以用作回答我的问题的接口。
    • 更新了答案。
    • 这个答案会很有帮助,但不幸的是我无法编辑界面(它在我正在使用的库中)所以我无法定义默认方法。
    • 好的,我现在明白了。更新了答案。创建一个抽象类来放置常用方法。以及特定剩余方法的普通类。
    • 那真是太糟糕了。如果是这样,我的问题的答案是:不,这在 java 中是不可能的,因为你最终需要实现所有方法。我想我现在会回答我自己的问题。感谢您的努力。
    猜你喜欢
    • 2021-02-10
    • 2018-07-16
    • 1970-01-01
    • 2021-08-29
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多