Explain the use of virtual, sealed, override, and abstract?
Abstract: The keyword can be applied for a class or method.
Class: If we use abstract keyword for a class it makes the class an abstract class, which means it cant be instantiated. Though it is not nessacary to make all the method within the abstract class to be virtual. ie, Abstract class can have concrete methods
Method: If we make a method as abstract, we dont need to provide implementation of the method in the class but the derived class need to implement/override this method.
Sealed: It can be applied on a class and methods. It stops the type from further derivation i.e no one can derive class from a sealed class,ie A sealed class cannot be inherited.A sealed class cannot be a abstract class.A compile time error is thrown if you try to specify sealed class as a base class. When an instance method declaration includes a sealed modifier, that method is said to be a sealed method. If an instance method declaration includes the sealed modifier, it must also include the override modifier. Use of the sealed modifier prevents a derived class from further overriding the method For Egs: sealed override public void Sample() { Console.WriteLine("Sealed Method"); }
Virtual & Override: Virtual & Override keyword provides runtime polymorphism. A base class can make some of its methods as virtual which allows the derived class a chance to override the base class implementation by using override keyword.
For e.g. class Shape
{
int a
public virtual void Display()
{
Console.WriteLine("Shape");
}
}
class Rectangle:Shape
{
public override void Display()
{
Console.WriteLine("Derived");
}
}
0 comments:
Post a Comment