Are abstract methods virtual?

Is it abstract that declaring an abstract method automatically makes it virtual?

That is, in subclasses I can override it many times and at runtime, the method corresponding to the type of runtime of the object will be called?

Is it possible to declare an abstract non-virtual method? That is, a method that must be implemented in a non-abstract subclass and cannot be overridden?

+7
source share
3 answers

Yes, abstract methods are virtual by definition; they must be redefined in order to actually be overridden by subclasses:

When an instance method declaration includes an abstract modifier, this method is called an abstract method. Although an abstract method is also an implicit virtual method , it cannot have a virtual modifier.

Conversely, you cannot declare an abstract non-virtual method, because if you could, you would have a method that cannot be implemented and therefore can never be called, which makes it useless.

However, if you want the class to implement an abstract method, but not allow any of its subclasses to change its implementation, then where is sealed . Example:

 abstract public class AbstractClass { abstract public void DoSomething(); } public class BaseClass : AbstractClass { public sealed override void DoSomething() { Console.WriteLine("Did something"); } } 

Note that although the abstract method is (implicitly) virtual, the implementation in a particular base class is not virtual (due to the sealed ).

+8
source

Yes, they are virtual. Otherwise, you will not be able to write an implementation for them.

+1
source

Yes, abstract methods are implicitly virtual. For this reason, you cannot use virtual modifier with static , abstract , private or override modifiers.

Logically speaking, why would anyone declare an abstract non-virtual method, because if you could, you would have a method that cannot be implemented and therefore can never be called, which makes it pretty pointless.

However, one of the main differences between them

Virtual methods have an implementation and provide derived classes with the ability to override. Abstract methods do not provide an implementation and force derived classes to override a method.

0
source

All Articles