Abstract Class:

Abstract Class:



  • An abstract class is a class that cannot be instantiated .i.e an class whose object cannot be made, trying to do so gives compile time error. 1.bmp


Above shown is the error when trying to create an object (obj) of an abstract class Class1


  • An abstract class is a class that can only be inherited by another class

public abstract class Class1

{


}


public class class2 : Class1

{


}

here Cass2 inherits Class1


  • An abstract method is a method with abstract keyword and with out any body or implementation of the method

public abstract class Class1

{


public abstract void add();

// add is an abstract method which is with out body its only the definition of the method


}


  1. an abstract method can not be private it has to be public, protected or internal

  2. there can be any number of abstract method in a abstract class

  3. an abstract method can not be written for non abstract class

  4. an abstract class can have other methods also which are not abstract methods

public abstract class Class1

{

public abstract void add();

private void sub()

{

}

}


    5.When an abstract class is inherited by another class ,the derived class which is inheriting the abstract class must have the implementation of the abstract method with override key word other wise it will give a compile time error as shown below2.bmp

the correct code for this is


public abstract class Class1

{

public abstract void add();


private void sub()

{

}

}


public class class2 : Class1

{

public override void add()

{

}

}


whats the use of an abstract class?
The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.

Example


using System;

using System.Collections.Generic;

using System.Text;


namespace AbstractClassEx

{

public abstract class Class1

{

public abstract void add();


private void sub()

{

}

}


public class class2 : Class1

{

public override void add()

{

throw new Exception("The method or operation is not implemented.");

}

}


}