views:

254

answers:

3

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?

Thanks

+7  A: 

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

Jon Skeet
Second 'C#' should be 'Java' in opening sentence.
eljenso
A: 

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.

Peter Lawrey
A: 

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.

ealgestorm
Do you also believe that private inheritance is only for "people who can't be bothered with good design"? That's another useful OOP capability missing from Java.
Ben Voigt
It will never be in Java for the same reason that delegates will never be in Java.. google it. There is a good article about why delegates where never done in Java and this is similar. It's bad because of what it allows you to do not the good stuff you can do with it. Something Microsoft and it's ecosystem don't get.
ealgestorm