Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. for F(). This alloes you to differently treat the object, corresponding to the current point of view: as IMyInterface1 or IMyInterface2. Is this possible in Java?

like image 740
lmsasu Avatar asked Feb 21 '09 19:02

lmsasu


2 Answers

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 (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).

like image 192
Jon Skeet Avatar answered Oct 12 '22 23:10

Jon Skeet


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();
    }
}
like image 27
Arteko Avatar answered Oct 13 '22 01:10

Arteko