Your Ad Here

Sunday, June 15, 2008

Implementing Polymorphism

/* The given C sharp example decalres abstract class Shape
* that implements polymorpism by overloading and
* overridding methods. The clas Shape2 consists
* of a virtual method ShapeType(). The method
* CalculateArea() is implemented twice by having
* different signatures and different return types.
* The class Square inherits the base class Shape2
* and overrides the base class method called ShapeType().
* The main() method creates an instance of the derieved
* class Square and the base class Shape2. the instance
* of the base class Shape2 invokes the method
* CalculateArea(). Depending on the parameter that
* the method CalcualteArea() takes, the apropiate
* method is called.
using System;

namespace Inherit
class Shape2
public virtual void ShapeType()
Console.WriteLine("This message will be used to display type of the shape");
public int CalculateArea(int side)
return side * side;
public double CalculateArea(double baseBreadth, double height)
return 05 * baseBreadth * height;
class Square :Shape2
public override void ShapeType()
Console.WriteLine("A square is a Polygon");
public static void Main(string[] args)
Square sqr = new Square();
Console.WriteLine("Area IS : "+sqr.CalculateArea(6));


//A square is a Polygon
//Area IS : 36

No comments: