Polymorphism in c# example source code
Output:
Source code:
using System;
namespace Inheritance
{
// class are by
default private it it
public class Shap
{
// if shap s=
new shap();
// this this
method call
public virtual double area()
{
return 0;
}
}
public class Circle:Shap
{
// if shap s=
new Circle();
// this this
method call
public override double area()
{
Console.WriteLine("Please enter the Radius of
the circle:");
double radius = Convert.ToDouble(Console.ReadLine());
double area = 2 * 3.1416 * radius;
return area;
}
}
public class Square:Shap
{
// if shap s=
new sqaure();
// this this
method call
public override double area()
{
Console.WriteLine("Please enter the length of
the square:");
double length = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please enter the length of
the square:");
double width = Convert.ToDouble(Console.ReadLine());
double area = length*width;
return area;
}
}
class main:Shap
{
static void Main(string[] args)
{
Console.WriteLine("-------------Polymorphism-------------");
Console.WriteLine("For Shap:\n");
// object of
shap polymorph for the shap
Shap sh = new Shap();
double ans = sh.area();
Console.WriteLine(ans);
Console.WriteLine("For Square:\n");
// object of
shap polymorph for the square
Shap s = new Square();
double ans1 = s.area();
Console.WriteLine(ans1);
Console.WriteLine("For Circle:\n");
// object of
shap ploymorph for the cirlce
Shap c = new Circle();
double ans2 = c.area();
Console.WriteLine(ans2);
Console.WriteLine("\nRules for
Polymorphsm:");
Console.WriteLine("----------------------------");
Console.WriteLine("1-Class are must be
inherited.");
Console.WriteLine("2-Parent class has one
method/function which is virtual.");
Console.WriteLine("3-Child classes has one
method/function which is override.");
Console.WriteLine("4-Both virtual and override
methods/functions must have same name.");
Console.WriteLine("5-method/function is not be static.");
{
}
}
}
}
Comments
Post a Comment