The Abstract Class modifier is used to define base classes which can be
derived by other classes. An Abstract class cannot be instantiated i.e we
cannot create objects from an Abstract class, trying to do so will result in a
compiler error.
Abstract class generally declare only the signature of the methods, the actual method body is coded in the derived class, however it doesn’t not stop us from adding a method body in the abstract class, we can still go ahead and do some code to the method body in the base abstract class.
Abstract class generally declare only the signature of the methods, the actual method body is coded in the derived class, however it doesn’t not stop us from adding a method body in the abstract class, we can still go ahead and do some code to the method body in the base abstract class.
The
following example creates a simple abstract
class, and a derived class which inherits from the Abstract class.
abstract class AbstractBaseClass
{
abstract public void AbstractBaseMethod();
}
//
class AbstractChildClass
: AbstractBaseClass
{
public override void AbstractBaseMethod()
{
}
}
Notice
that the methods of the abstract class
are also marked as abstract, this is mandatory if the methods do not have any
implementation, if the methods do not have an implementation and if they are
not declared abstract then a compiler error will be thrown as follows.
abstract class AbstractBaseClass
abstract class AbstractBaseClass
{
abstract public void AbstractBaseMethod();
public void
NonAbstractBaseMethod();
}
Error: AbstractBaseClass.NonAbstractBaseMethod() must declare a body because it is not marked abstract, extern, or partial
Error: AbstractBaseClass.NonAbstractBaseMethod() must declare a body because it is not marked abstract, extern, or partial
As
stated in the error, if we add a method body to the non abstract method then
the error will not occur.
abstract class AbstractBaseClass
{
abstract public void AbstractBaseMethod();
public void
NonAbstractBaseMethod()
{
//Implementation goes here.
}
}
No comments:
Post a Comment