Abstract class and sealed class
Defines abstract and sealed classes which are more advanced types of classes
A class defined as abstract is used as a base class. Such a class is used for the purpose of inheritance only i.e. other classes are derived from this class. We cannot create an object of an abstract class.
The syntax for creating an abstract class is:
abstract class class-name
{
// members of the class
}
An abstract class may contain methods and properties. The classes derived from the abstract class inherit these methods and properties. The abstract class may also contain abstract methods and properties. Abstract method and properties do not have any functionality. The derived class defines their full functionality.
Here is an example of an abstract class:
abstract class MyAbstract { public abstract void AbMethod(); }
In the above example, the class MyAbstract is defined as an abstract class. The class contains a method - AbMethod() - also defined as abstract. Note that the method does not have any implementation i.e. we have not specified what the method is doing.
If we create an object of this class, we will get an error. This is because we cannot create objects of an abstract class. To use this class in a program, we must first create a class that inherits from this abstract class:
class MyDerived : MyAbstract {
public override void AbMethod() { Console.WriteLine("A Method");
} }
The MyDerived class is derived from the MyAbstract class. The derived class also provides the complete implementation of the abstract method. We should use the override keyword in such a case. This MyDerived class can have its objects in the program.
A class defined with the keyword sealed is used to prevent derivation from it i.e. other classes cannot inherit from this class. Hence, a sealed class cannot be a base class for other classes. A sealed class cannot be abstract as well.
The syntax for a sealed class definition is:
sealed class class-name
{
//members of the class