简体   繁体   English

Java 中是否存在接口的 C#“显式实现”?

[英]Is the C# “explicit implementation” of the interface present in Java?

In C#, if you have two base interfaces with the same method (say, F()) you can use explicit implementation to perform different impl.在 C# 中,如果您有两个具有相同方法的基本接口(例如 F()),您可以使用显式实现来执行不同的实现。 for F().对于 F()。 This alloes you to differently treat the object, corresponding to the current point of view: as IMyInterface1 or IMyInterface2.这允许您根据当前的观点对对象进行不同的处理:作为 IMyInterface1 或 IMyInterface2。 Is this possible in Java?这在Java中可能吗?

No, there's nothing like C#'s explicit interface implementation in Java.不,没有什么比 C# 在 Java 中的显式接口实现更像的了。

On the plus side, Java has covariant return types, so if you want to provide a more strongly typed implementation than the interface specifies, that's okay.从好的方面来说,Java 具有协变返回类型,因此如果您想提供比接口指定的更强类型的实现,那也没关系。 For instance, this is fine:例如,这很好:

interface Foo
{
    Object getBar();
}

public class Test implements Foo
{
    @Override
    public String getBar()
    {
        return "hi";
    }
}

C# wouldn't allow that (prior to C# 9, which now supports covariant return types ) - and one of the ways around it is typically to implement the interface explicitly and then have a more specific public method (usually called by the interface implementation). C# 不允许这样做(在 C# 9 之前, 现在支持协变返回类型) - 解决它的方法之一通常是显式实现接口,然后有一个更具体的公共方法(通常由接口实现调用) .

You can achieve similar effect using the mechanism of anonymous interface implementation in Java.您可以使用 Java 中匿名接口实现的机制来实现类似的效果。

See example:见示例:

interface Foo {

    void f();
}

interface Bar {

    void f();
}

public class Test {

    private String foo = "foo", bar = "bar";

    Foo getFoo() {
        return new Foo() {

            @Override
            public void f() {
                System.out.println(foo);
            }
        };
    }

    Bar getBar() {
        return new Bar() {

            @Override
            public void f() {
                System.out.println(bar);
            }
        };
    }

    public static void main(String... args) {
        Test test = new Test();
        test.getFoo().f();
        test.getBar().f();
    }
}

You can only do this if the methods are overloaded.只有在方法重载时才能执行此操作。 If you have two method which are expected to do different things, they should have different names IMHO.如果您有两种方法可以做不同的事情,恕我直言,它们应该有不同的名称。

No and it should never be present in Java.不,它永远不应该出现在 Java 中。 It's just another bone to throw at people who can't be bothered with good design.这只是向那些不会被良好设计所困扰的人扔的另一块骨头。

Explicit implementation of an interface should never be needed or used.永远不需要或使用接口的显式实现。 There are better ways to solver the problem that this tries to solve.有更好的方法来解决这个试图解决的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM