Am I correct that declaring a method abstract
automatically makes it virtual?
That is, in subclasses I can override it many times and at runtime, the method corresponding to the runtime type of the object will be called?
Is it possible to declare an abstract non-virtual method? That is, the method which must be implemented in a non-abstract subclass and can not be overridden?
[7] An abstract method in Java is something like a pure virtual function in C++ (i.e., a virtual function that is declared = 0). In C++, a class that contains a pure virtual function is called an abstract class and cannot be instantiated. The same is true of Java classes that contain abstract methods.
Answer: Yes, We can have virtual method in an Abstract class in C#. This is true that both virtual and abstract method allow derived classes to override and implement it. But, difference is that an abstract method forces derived classes to implement it whereas virtual method is optional.
Abstract methods do not provide an implementation and force the derived classes to override the method. Virtual methods have an implementation and provide the derived classes with the option of overriding it.
An abstract function has to be overridden while a virtual function may be overridden. Virtual functions can have a default /generic implementation in the base class.
Yes, they are virtual. Otherwise you would have no way to write implementation for them.
Yes, abstract methods are virtual by definition; they must be overridable in order to actually be overridden by subclasses:
When an instance method declaration includes an
abstract
modifier, that method is said to be an abstract method. Although an abstract method is implicitly also a virtual method, it cannot have the modifiervirtual
.
Conversely you can't declare an abstract non-virtual method, because if you could, you would have a method that can't be implemented and thus can never be called, making it rather useless.
However, if you want to have a class implement an abstract method but not allow any of its subclasses to modify its implementation, that's where sealed
comes in. An example:
abstract public class AbstractClass
{
abstract public void DoSomething();
}
public class BaseClass : AbstractClass
{
public sealed override void DoSomething()
{
Console.WriteLine("Did something");
}
}
Notice that while the abstract method is (implicitly) virtual, the implementation in the concrete base class is non-virtual (because of the sealed
keyword).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With