Sealing an interface after implementing it

前端 未结 5 427
天命终不由人
天命终不由人 2021-01-02 16:00

I am working on a small project and I came across that problem.

The project output is a library containing an interface. I would like to implement that interface and

5条回答
  •  隐瞒了意图╮
    2021-01-02 16:46

    Your understanding of sealed keyword is incorrect. As a method modifier, sealed is used to prevent a virtual method(defined in the base class) to be override in the next generation of derived classes. For example:

    class Base
    {
       public virtual void M() { }
    }
    
    class Derived : Base
    {
       public sealed override void M() { }
    }
    
    class A : Derived
    {
       public override void M() { } //compile error, M is sealed in Derived
    }
    

    Developers can always use new modifier to define a method with the same name in the derived class, that hides the one defined in the base class.

    if someone create a specialized class of type A, he/she won't be able to change the method's behavior.

    If "specialized class" means a class derived from A, the answer is: he can always hide the method in A, but he can't change the method's behavior.

提交回复
热议问题