Home > front end >  Access modifiers nbot permitted when provided explicit implementation for interface member in imleme
Access modifiers nbot permitted when provided explicit implementation for interface member in imleme

Time:08-02

interface honda {

    void meth();
    protected void meth2();
}

class crv : honda { 
    void honda.meth() { }  //public not allowed
    void honda.meth2() { } //protected not allowed
}

I gave interface honda that has 2 abstract methods:
meth(); which is public
meth2(); which is protected

Whay do I get an error when i say public void honda.meth(){} or protected honda.meth2() { } in the implementing class crv?

I mean i have one assumption: It is beacuse by doing this, we provide default implementation for the method, so It is like in the interface but It is not. This assumption wpuld justify the error when I say public void honda.meth(){} but it does not justify the error whjen I try to say protected honda.meth2() { } since the meth2() is protected in the interface.
Could you please help me?

CodePudding user response:

By declaring the methods in the implementing class as honda.meth, this is an explicit interface implementation. Basically, it means that these methods can only be called on an object of type honda, not crv so the access modifiers on crv are never going to be used.

If you wanted to be able to call these methods on types of both honda and crv, simply drop the honda. prefix from the method name in the implementing class like so:

interface honda {

    void meth();
    void meth2();
}

class crv : honda { 
    public void meth() { } 
    public void meth2() { }
}

Note that you can't specify an access modifier in an interface (public, protected etc.) unless you are using the default implementations in interfaces C# feature.

If meth2 had to be protected, change honda to be an abstract class and meth2 to be an abstract method:

public abstract class honda {
    
   public abstract void meth();
   protected abstract void meth2();

}
  • Related