Wednesday, 13 August 2014

Abstract Class and Abstract Method
An abstract class is a class that is declared abstract. it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be derived. An abstract class means that, no object of this class can be instantiated, but can make derivations of this.

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

abstract class BaseClass
{

}

You can also define the abstract method / Non abstract method inside abstract class as
abstract class BaseClass
{
  public abstract void abstractMethod();
  public void nonAbstractMethod()
  {

  }
}


Note following points while creating the abstract class / abstrtact method

Ø  Abstract class can have abstract / non abstract methods, properties, events.
Ø  Abstract class cannot be sealed class.
Ø  If method is an abstract then it should defined with public / protected & name preceded by abstract keyword.
Ø  Abstract method cannot be private.
Ø  If method is non abstract then it should have body.
Ø  Abstract method cannot be defined in the non abstract class. Simply Abstract method declarations are only permitted in abstract classes
Ø  The access modifier of the abstract method should be same in both the abstract class and its derived class.
Ø  An abstract method cannot have be virtual / static. Abstract method is implicitly virtual.
Ø  It is an error to use the abstract modifier on a static property or method.
Ø  It is an error to use the abstract modifier on a virtual property or method.
Ø  It is an error to use private access modifier to abstract method / property.


How use abstract  methods in derived class  
   abstract class BaseClass
    {
        public abstract void abstractMethod();
        public void nonAbstractMethod()
        {

        }

    }

    class DerivedClass : BaseClass
    {


        public override void abstractMethod()
        {
           
        }
    }


Note following points while creating the derived class from abstract class

Ø  You must give override keyword to the abstract method in derived class
Ø  It will give error if you cannot override the abstract method in the derived class
Ø  You cannot override the  non-abstract method
Ø  Signature of abstract method / property in base class must be same with signature of override method / property in derived class only difference is abstract / override keyword


When to use Abstract Class

Ø  You want to share code among several closely related classes.
Ø  You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
Ø  You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong







No comments:

Post a Comment