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

前端 未结 4 1701
忘掉有多难
忘掉有多难 2020-12-17 14:23

In C#, if you have two base interfaces with the same method (say, F()) you can use explicit implementation to perform different impl. for F(). This alloes you to differently

相关标签:
4条回答
  • 2020-12-17 14:48

    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.

    0 讨论(0)
  • 2020-12-17 15:02

    You can achieve similar effect using the mechanism of anonymous interface implementation in 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();
        }
    }
    
    0 讨论(0)
  • 2020-12-17 15:07

    No, there's nothing like C#'s explicit interface implementation in 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. 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 - 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).

    0 讨论(0)
  • 2020-12-17 15:08

    No and it should never be present in 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.

    0 讨论(0)
提交回复
热议问题