开发者

When you implement an interface in Java is it explicit or implicit?

开发者 https://www.devze.com 2022-12-22 02:36 出处:网络
I just started figuring out the difference between implicit and explicit interface implmentation in .Net. Since I come from a Java background the idea is still a bit confusing. I am hoping knowing whi

I just started figuring out the difference between implicit and explicit interface implmentation in .Net. Since I come from a Java background the idea is still a bit confusing. I am hoping knowing which Java does will make it more obvious what the difference is. I am assuming the Java is explicit开发者_运维知识库???


Nope Java is implicit. Explicit is where you are implementing multiple interfaces that have the same method signatures in them and you explicitly state which interface the implementation is for.

An example from MSDN:

public class SampleClass : IControl, ISurface
{
    void IControl.Paint()
    {
        System.Console.WriteLine("IControl.Paint");
    }
    void ISurface.Paint()
    {
        System.Console.WriteLine("ISurface.Paint");
    }
}

Here we have two Paint() methods, one from each interface. In Java you can only have one Paint() implementation. In C# you have the option of implementing versions for each interface so you get different behaviour depending how the class is called.

So if I called:

SampleClass c = new SampleClass();
((IControl)c).Paint();
((ISurface)c).Paint();

I'd get "IControl.Paint" printed out followed by "ISurface.Paint" printed out.


In Java there is no distinction between explicit and implicit. If you have two interfaces that both declare a method with the same signature, and a class that implements both interface, then a method in the class with the correct signature implements the method in BOTH interfaces.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号