Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Characteristics of the abstract class

Tags:

c#

oop

I would like to know what makes a class to be called as an abstract class. I believe, abstract keyword definitely make a class, but if one takes out the keyword, then we can create the instance of the class.

In otherwords, what are the characteristics of the abstract class.

Thanks in advance.

-Harsha

like image 509
Harsha Avatar asked Jan 22 '26 04:01

Harsha


1 Answers

An abstract class does not form a concrete object in the real world unlike pure implementation classes. Abstract as the name suggestes they hold/define common behaviours of related objects that need to be reused/defined independantly in all related objects.

Take an example of Birds. If you are writing a progrm that will have something to do with the birds, then you'll first have an abstract base class as Bird and each bird deriving from the abstract base class Bird. Do note that abstract class BIRD does not represent a concrete real world object but a type of related objects that is birds!

Lets start with the class-diagram and then some code.

alt text http://ruchitsurati.net/files/birds.png

public abstract class Bird
{
    protected string Name = string.Empty;
    public Bird(string name)
    {
        this.Name = name;
    }

    public virtual void Fly()
    {
        Console.WriteLine(string.Format("{0} is flying.", this.Name));
    }

    public virtual void Run()
    {
        Console.WriteLine(string.Format("{0} cannot run.", this.Name));
    }
}

public class Parrot : Bird
{
    public Parrot() : base("parrot") { }
}

public class Sparrow : Bird
{
    public Sparrow() : base("sparrow") { }
}

public class Penguin : Bird
{
    public Penguin() : base("penguin") { }

    public override void Fly()
    {
        Console.WriteLine(string.Format("{0} cannot fly. Some birds do not fly.", this.Name));
    }

    public override void Run()
    {
        Console.WriteLine(string.Format("{0} is running. Some birds do run.", this.Name));
    }
}

class Program
{
    static void Main(string[] args)
    {

        Parrot p = new Parrot();
        Sparrow s = new Sparrow();
        Penguin pe = new Penguin();

        List<Bird> birds = new List<Bird>();

        birds.Add(p);
        birds.Add(s);
        birds.Add(pe);

        foreach (Bird bird in birds)
        {
            bird.Fly();
            bird.Run();
        }

        Console.ReadLine();
    }
}
like image 175
this. __curious_geek Avatar answered Jan 24 '26 21:01

this. __curious_geek