An
abstract class cannot be instantiated. The purpose of an abstract class is to
provide a common definition of a base class that multiple derived classes can
share. For example, a class library may define an abstract class that is used
as a parameter to many of its functions, and require programmers using that
library to provide their own implementation of the class by creating a derived
class. Abstract classes may also define abstract
methods. This is accomplished by adding the keyword abstract before the return type
of the method
The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a
derived class.
If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method.
Syntax:
public abstract class
A
{
public abstract void DoWork(int
i);
}
If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method.
Implementation:
//
compile with: /target:library
public class
D
{
public virtual void DoWork(int i)
{ // Original implementation. }
}
public abstract class
E : D
{
public abstract override void
DoWork(int i);
}
public class
F : E
{
public override void DoWork(int
i)
{ // New implementation.}
}
Source Code
Important rules applied to abstract classes:
Important rules applied to abstract classes:
- An abstract class cannot be a sealed class.
Example: Abstract sealed class
absClass {}
- Declaration of abstract methods is only allowed in abstract classes.
- An abstract method cannot be private
- The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.
- An abstract method cannot have the modifier virtual. Because an abstract method is implicitly virtual.
- An abstract member cannot be static.
No comments:
Post a Comment