OOP

how to prevent the subclass method from overriding the base class

+2


source to share


3 answers


You don't have to do anything special: functions are not overridden by default. Rather, if you want a method to be overridden, you need to add a keyword virtual

to its declaration.



Note that even if the method is not overridden, the derived class can hide it. More info here: Using the C # virtual + override vs. new

+10


source


If you have a virtual method in a base class (ClassA) that is overridden in an inherited class (ClassB), and you want a class that inherits from ClassB to override that method, then you must mark this method as "sealed" in ClassB.



public class ClassA
{
    public virtual  void Somemethod() {}
}

public class ClassB : ClassA
{
    public sealed override void Somemethod() {}
}

public class ClassC : ClassB
{
     // cannot override Somemethod here.
}

      

+7


source


You can also use ABSTRACT on the parent class. As a result, you cannot override the subclass

abstract main{
}

class sub extent main{
}

      

-1


source







All Articles