Click here to Skip to main content
Email Password   helpLost your password?

Introduction

Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes that only represent base classes, and don�t want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract'.

An abstract class means that, no object of this class can be instantiated, but can make derivations of this.

An example of an abstract class declaration is:

abstract class absClass
{
}

An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.

An example of an abstract method:

abstract class absClass
{
  public abstract void abstractMethod();
}

Also, note that an abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract members. For example:

abstract class absClass
{
    public void NonAbstractMethod()
    {
        Console.WriteLine("NonAbstract Method");
    }
}

A sample program that explains abstract classes:

using System;

namespace abstractSample
{
      //Creating an Abstract Class

      abstract class absClass
      {
            //A Non abstract method

            public int AddTwoNumbers(int Num1, int Num2)
            {
                return Num1 + Num2;
            }

            //An abstract method, to be

            //overridden in derived class

            public abstract int MultiplyTwoNumbers(int Num1, int Num2);
      }

      //A Child Class of absClass

      class absDerived:absClass
      {
            [STAThread]
            static void Main(string[] args)
            {
               //You can create an

               //instance of the derived class


               absDerived calculate = new absDerived();
               int added = calculate.AddTwoNumbers(10,20);
               int multiplied = calculate.MultiplyTwoNumbers(10,20);
               Console.WriteLine("Added : {0}, 
                       Multiplied : {1}", added, multiplied);
            }

            //using override keyword,

            //implementing the abstract method

            //MultiplyTwoNumbers

            public override int MultiplyTwoNumbers(int Num1, int Num2)
            {
                return Num1 * Num2;
            }
      }
}

In the above sample, you can see that the abstract class absClass contains two methods AddTwoNumbers and MultiplyTwoNumbers. AddTwoNumbers is a non-abstract method which contains implementation and MultiplyTwoNumbers is an abstract method that does not contain implementation.

The class absDerived is derived from absClass and the MultiplyTwoNumbers is implemented on absDerived. Within the Main, an instance (calculate) of the absDerived is created, and calls AddTwoNumbers and MultiplyTwoNumbers. You can derive an abstract class from another abstract class. In that case, in the child class it is optional to make the implementation of the abstract methods of the parent class.

Example

//Abstract Class1

abstract class absClass1
{
    public abstract int AddTwoNumbers(int Num1, int Num2);
    public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}

//Abstract Class2

abstract class absClass2:absClass1
{
    //Implementing AddTwoNumbers

    public override int AddTwoNumbers(int Num1, int Num2)
    {
        return Num1+Num2;
    }
}

//Derived class from absClass2

class absDerived:absClass2
{
    //Implementing MultiplyTwoNumbers

    public override int MultiplyTwoNumbers(int Num1, int Num2)
    {
        return Num1*Num2;
    }
}

In the above example, absClass1 contains two abstract methods AddTwoNumbers and MultiplyTwoNumbers. The AddTwoNumbers is implemented in the derived class absClass2. The class absDerived is derived from absClass2 and the MultiplyTwoNumbers is implemented there.

Abstract properties

Following is an example of implementing abstract properties in a class.

//Abstract Class with abstract properties

abstract class absClass
{
    protected int myNumber;
    public abstract int numbers
    {
        get;
        set;
    }
}

class absDerived:absClass
{
    //Implementing abstract properties

    public override int numbers
    {
        get
        {
            return myNumber;
        }
        set
        {
            myNumber = value;
        }
    }
}

In the above example, there is a protected member declared in the abstract class. The get/set properties for the member variable myNumber is defined in the derived class absDerived.

Important rules applied to abstract classes

An abstract class cannot be a sealed class. I.e. the following declaration is incorrect.

//Incorrect

abstract sealed class absClass
{
}

Declaration of abstract methods are only allowed in abstract classes.

An abstract method cannot be private.

//Incorrect

private abstract int MultiplyTwoNumbers();

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.

//Incorrect

public abstract virtual int MultiplyTwoNumbers();

An abstract member cannot be static.

//Incorrect

publpublic abstract static int MultiplyTwoNumbers();

Abstract class vs. Interface

An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.

An example of interface:

interface iSampleInterface
{
  //All methods are automaticall abstract

  int AddNumbers(int Num1, int Num2);
  int MultiplyNumbers(int Num1, int Num2);
}

Defining an abstract class with abstract members has the same effect to defining an interface.

The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.

A class can inherit one or more interfaces, but only one abstract class.

Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.

The selection of interface or abstract class depends on the need and design of your project. You can make an abstract class, interface or combination of both depending on your needs.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralSomething to add....
Nirosh
0:42 4 Mar '10  
>I guess it is good to note that You can also pass something via the constructor like this too..


public abstract class RepositoryBase<T> : IRepository<T> where T: class {
public RepositoryBase(IObjectSet<T> objectSet)
{
_objectSet = objectSet;
}

private IObjectSet<T> _objectSet;
public IObjectSet<T> ObjectSet
{
get
{
return _objectSet;
}
}
}
___________________________________________

public class FileRepository : RepositoryBase<DocFile>, IFileRepository
{
public FileRepository(IObjectSet<DocFile> objectSet)
: base(objectSet)
{
}
}
- A random opportunity is like a taller chair, those who sit hang on, those who hang on fall
L.W.C. Nirosh.
Colombo,
Sri Lanka.

GeneralFrom Vishal Sanchihar
vishalsan007
2:26 14 Apr '08  
Nice article, with full detail...
GeneralUse an abstract class
Manasu
22:18 6 Aug '07  

When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. (COM was designed around interfaces.)
Use an abstract class to define a common base class for a family of types.
Use an abstract class to provide default behavior.
Subclass only a base class in a hierarchy to which the class logically belongs.

manasu

Generalsee this also
objectspot
3:23 5 Jul '06  
http://objectspot.blogspot.com/[^]
GeneralPolymorphism
binhtt@fsoft.com.vn
1:53 22 Sep '05  
We can implement polymorphism with interface but we can with abstract
GeneralRe: Polymorphism
Chintan.Desai
22:29 6 Aug '08  
Polymorphism will violates abstract class rules. Abstract class method signature and access privelege must be same in the derived class.

Thanks,
Chintan(India)

GeneralPraveen Kasana
praveen kasana
21:01 24 Aug '05  
This article really helped me ,thanksRose
GeneralNice article
tintokthomas2005
21:42 7 May '05  
nice and easy to understand

Regards
Tinto
GeneralNice article and good correction
Kulkarni Prafulla
19:26 4 Mar '04  
Nice article Jayababu.

And also good correction suggested by Maximilian.

Prafulla.
GeneralGood
Kant
7:02 27 Feb '04  
It would be cool if you can go deep and can cover virtual modifier and sealed class topics too.

My 4.


Promise only what you can do. And then deliver more than what you promised.

This signature was created by "Code Project Quoter".
GeneralRe: Good
Jayababu
22:49 1 Mar '04  
Thanks Kant for your comments.
I will do the needful.
rgds
Jayababu
GeneralRe: Good
Chintan.Desai
22:32 6 Aug '08  
You can fine very good article over here...
http://msdn.microsoft.com/en-us/library/88c54tsw

Thanks,
Chintan(India)

GeneralNice Job...
Matthew Hazlett
21:46 26 Feb '04  
Very good posting..

Matthew Hazlett
Windows 2000/2003 MCSE
Never got an MCSD, go figure...
GeneralCorrection
Maximilian Hänel
21:39 18 Feb '04  
An abstract class indicates that the class is incomplete and that has to be used as a base class This is wrong. abstract doesn't mean that a class is incomplete and/or must be overriden. It only means that no instances of this class could be created - nothing else. The following code is totally legal:

public abstract class DemoClass
{
public static void DoSomething()
{
}
}

//..
DemoClass.DoSomething();

cu

Max

"All languages allow you to write crap code, VB just makes it easier (IMO)." Michael P Butler

GeneralRe: Correction
Jayababu
22:08 18 Feb '04  
Hi Max,
Thanks for your comments. Its the problem with the word "incomplete", will make confusion. I will make necessary updations in the article.

Thanks and Rgds
Jayababu
GeneralRe: Correction
Maximilian Hänel
4:02 19 Feb '04  
Hi Jayababu,

Actually I think that the most confusing part of abstract is that it can't be used in combination with the sealed keyword (wich is IMHO a design error). So if a programmer sees a class marked as abstract but not sealed the first obvious thougt is that this class must be overriden to be usable. There are however many classes that should neither be instantiated nor be derived from, that is classes with only static stuff in it (Application, SystemInformation, Brushes, to name a few of them). So we end up in writing
sealed class OnlyStaticStuff
{
private OnlyStaticStuff(){}// Dummy Ctor to prevent instantiation
//only static stuff here
}
rather than
//doesn't compile
abstract sealed class OnlyStaticStuff
{
//only static stuff here
}

Implementing a private ctor to prevent instantiation is of course not a big deal in practice, but it's a kind of hack if you want, so in Widbey we will get a static on class level:

static sealed class OnlyStaticStuff
{
//only static stuff here
}

cu

Max

"All languages allow you to write crap code, VB just makes it easier (IMO)." Michael P Butler

GeneralRe: Correction
S. Senthil Kumar
4:17 19 Feb '04  
Hi,

Of what use is a Abstract class if it can't be derived from? The basic purpose of Abstract classes is to make sure that derived members can provide their own implementations of some methods, while using some other methods in the base class.

Regards
Senthil
GeneralRe: Correction
Maximilian Hänel
7:23 19 Feb '04  
Of what use is a Abstract class if it can't be derived from? As I mentioned in a previous post: To ensure/indicating that a class can not be instantiated. In many (if not all) cases it doesn't make sense to derive from pure static classes. It also doesn't make sense to instantiate such a (pure static) class. So this would be a perfect example of an abstract sealed class.

The basic purpose of Abstract classes is to make sure that derived members can provide their own implementations of some methods, while using some other methods in the base class. That's what it is used for most of the time (due to the not allowed abstract/sealed combination). But as I mentioned earlier it is neither a constraint that an abstract class must be derived from nor that it is in any way incomplete. In the end effect abstract only prevents instantiation - that's the only real constraint abstract forces.

"All languages allow you to write crap code, VB just makes it easier (IMO)." Michael P Butler

GeneralRe: Correction
Jayababu
8:49 19 Feb '04  
Hi Max,

I have made necessary changes in the article, and sent the same to codeproject to update it in the site.

Thanks and Rgds
Jayababu
GeneralRe: Correction
Anonymous
6:19 4 Jan '05  
To prevent inheritence and instantiation use a sealed class with a private constructor.
AnswerRe: Correction
Raj Chudasama
7:25 9 Jul '07  
This is from EMCA C# language specification June 2006 Page 267 if printed (286 of the pdf file)

17.1.1.1 Abstract classes
The abstract modifier is used to indicate that a class is incomplete and that it is intended to be used only
as a base class.
An abstract class differs from a non-abstract class in the following ways:
• An abstract class cannot be instantiated directly, and it is a compile-time error to use the new operator on
an abstract class. While it is possible to have variables and values whose compile-time types are
abstract, such variables and values will necessarily either be null or contain references to instances of
non-abstract classes derived from the abstract types.
• An abstract class is permitted (but not required) to contain abstract members.
• An abstract class cannot be sealed.
When a non-abstract class is derived from an abstract class, the non-abstract class shall include actual
implementations of all inherited abstract members, thereby overriding those abstract members. [Example: In
the following code
abstract class A
{
public abstract void F();
}
abstract class B: A
{
public void G() {}
}
class C: B
{
public override void F() {
// actual implementation of F
}
}
the abstract class A introduces an abstract method F. Class B introduces an additional method G, but since it
doesn’t provide an implementation of F, B shall also be declared abstract. Class C overrides F and provides
an actual implementation. Since there are no abstract members in C, C is permitted (but not required) to be
non-abstract. end example]
If one or more parts of a partial type declaration (§17.1.4) of a class include the abstract modifier, the
class is abstract. Otherwise, the class is non-abstract.



If one says write code that is reuseable and understandable by others, SLAP HIM. (YOU WOULD ASK "WHY" ONLY IF YOU ARE STUPID)
Smile haha, i just pulled that out of my butt.

Generalseems good..
APSSidhu
19:22 18 Feb '04  
This artical has given a good insight on the Abstract classes . author has tried to tackel many view points .so i rate this artical high average.

Amarpreet Singh Sidhu


Last Updated 27 Feb 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010