Thursday, November 25, 2010

Understanding the abstract Methods in Console application.

When using inheritance relationship, you can have a situation where you want a method in a class to be implemented differently in the derived classes but not by the base class itself. Abstract methods are the methods without any body. The implementation of an abstract method is done by the derived class. When a derived class inherits the abstract method from the abstract class, it must override the abstract methods. This requirement is enforced at compile time, and is also called dynamic polymorphism.

The syntax for using the abstract method is:

[access-modifiers] abstract return-type method-name ([parameters]);

Example:

Using System;
Abstract class Animal
  {
      public abstract void Foodhabits( )
   }
     class Carnivorous: Animal
       {
       punlic override void FoodHabits( )
           {

         console.WriteLine(“The carnivorous animals eat only meat”);
         }
     }
  class Herbivorous : Animal
       {
    public override void FoodHabits( )
      {
     Console.writeLine(“The Carnivorous animals eat only plants”);
          }
       }
     class Implement
       {
     public static void Main ( )
      {
      Carnivorous cn = new carnivorous( );
      Herbivorous hb=  new Herbivorous( );

       Cn.,FoodHabits( );
      Hb.FoodHabits( );
         }
}

NOTE: - The abstract method is declared by adding the abstract modifier to the method. Abstract method FoodHabits() is declared in the abstract class Animal and then the abstract method is inherited in Carnivorous and Herbivorous Class. Abstract methods cannot contain any method body. 

No comments:

Recent Posts