Abstract class (OOP principle)

Qus :- What is Abstract class ?
Ans :- Abstraction is one of the principle of object oriented programming. If a class is defined as abstract then we can’t create an instance of that class. It is used to display only necessary and essential features of an object.
Basic Concepts :
     1. An abstract base class can not be instantiated; it means the object of that class can not be created.
      2. If an abstract class’s all method is abstract then this class will be a pure abstract base class.
     3. An abstract class holds the methods, but the actual implementation of those methods is made in derived class.
Real world example : (Take an example of a car)
     We know a car has below things :
            a) Color         b) Steering          c) Gear          d) Mirror               e) Brakes
            f) Exhaust System        g) Diesal Engine         h) Battery              i) Engine etc
     Before starting a car we must know below necessary things :
              a) Color          b) Steering       c) Mirror        d) Brakes and   e) Gear
     these are abstract methods. 
     We no need to know below things :
             a) Internal details of a car     b) Engine       c) Diesal Engine      d) Exhaust System etc.
     These are Encapsulate.
Coding Example : (Console application)
                   Declare an abstract class named Animal, which has an abstract method named Eat() and a normal method named Sound().

    abstract class Animal
        public abstract string Eat();
        public string Sound() 
            return “Dog can sound. (From Animal)”;

                     Now declare a derive class named Dog which inherited Animal abstract class and has one override method named Eat()

    class Dog : Animal

        public override string Eat()
            return “Dog can eat. (From Dog)”;

    Now we are going to run this code.

    class Program
        static void Main(string[] args)
            Dog oDog = new Dog();
            string a = oDog.Sound();
            string b = oDog.Eat();

            //Animal oAnimal = new Animal(); //Cannot create an instance of the abstarct class

            Animal oAnimal = new Dog();

            string c = oAnimal.Eat();

            Console.Write(“{0} n{1} n{2}”, a, b, c);


Here we can see :-
oDog.Sound() => returns base class (Animal) method result.
oDog.Eat() = > returns deirve class (Dog) method result.
oAnimal.Eat() => it also return derive class (Dog) method result.

Leave a Reply