Sunday 19 August 2018

C#: Abstract classes

Abstract Method
An abstract method is a method that is declared without implementation. An abstract method is declared using the keyword abstract.

Syntax
abstract returnType methodName(parameters)

Example
abstract int sum(int operand1, int operand2);

Abstract Class
An abstract class is declared using the keyword abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be sub classed.

Syntax
    abstract class ClassName{
        /* may or may not contain abstract methods */
    }

If a class extends the abstract class, then it must provide the implementation for all the abstract methods in the abstract class, otherwise the class should be declared as abstract.

The main purpose of abstract class is to use the common code in the sub classes.

Program.cs
using System;

abstract class Animal
{
    String name;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public abstract String run();
}

class Elephant : Animal
{
   public override String run(){
        return "I can run at the speed of 25 mph";
    }
}

class Lion : Animal
{
    public override String run(){
        return "I can run at the speed of 50 mph";
    }
}

class Tiger : Animal
{
    public override String run(){
        return "I can run at the speed of 60 mph";
    }
}


class Program
{
    static void Main(string[] args)
    {
        Animal anim1 = new Elephant();
        anim1.setName("Gaja");
        Console.WriteLine(anim1.getName() + ":" + anim1.run());

        anim1 = new Lion();
        anim1.setName("Aslam");
        Console.WriteLine(anim1.getName() + ":" + anim1.run());

        anim1 = new Tiger();
        anim1.setName("PTR");
        Console.WriteLine(anim1.getName() + ":" + anim1.run());

    }
}


Output
Gaja:I can run at the speed of 25 mph
Aslam:I can run at the speed of 50 mph
PTR:I can run at the speed of 60 mph

Every Animal has a name, so getName() and setName() are common to all the animals, So the implementation for these methods kept in the abstract class Animal. Whereas different Animals runs at different speeds, so the run() method declared as abstract, so all the concrete classes that are extending the class Animal, must provide the implementation for the run method.

Note

You can't create instances to abstract classes.




Previous                                                 Next                                                 Home

No comments:

Post a Comment