您的位置:首页 > 编程语言 > C#

C# 虚方法

2016-05-16 20:00 465 查看
虚方法,就是可以在派生类中对其实现进一步改进的方法,也称之为方法覆盖。

示例代码:

using System;
using System.Collections.Generic;
using System.Text;

namespace 虚方法
{
class plant      //定义基类
{
public virtual void area()  //定义虚方法area
{

}
}

class rectangle : plant
{
float lg;
float wh;
double ar;
public rectangle(float l,float w)      //定义构造函数,对长和宽进行初始化
{
lg = l;
wh = w;
}
public override void area()           //覆盖基类中的虚方法,计算输出矩形面积
{
ar = lg * wh;
Console.WriteLine("The Area of Rectangle is :" + ar);
}
}

class triangle : plant
{
float hem;
float high;
double ar;
public triangle(float h, float hi)
{
hem = h;
high = hi;
}
public override void area()
{
ar = 0.5 * hem * high;
Console.WriteLine("The area of Triangle is :" + ar);
}
}

class Program
{
static void Main(string[] args)
{
rectangle rec = new rectangle(6, 5);
triangle tri = new triangle(6, 5);
rec.area();
tri.area();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: