C# 多态典型练习题

来源:转载



多态典型练习题:


例题:利用多态实现计算器Calc,
将加减乘除四则运算看作一种操作,请设计操作抽象类Operation,
该抽象类有一个Op的方法计算两个整数相应运算,并返回计算结果。
并派生出四则运算操作类。计算器一个方法Do方法,实现四则运算并绘制整个程序的uml图。


using System;
namespace polymorphic
{
/*
*
*/
class Program
{
static void Main(string[] args)
{
Calc c = new Calc();
Add add = new Add(20, 10);
Console.WriteLine("结果等于:" + c.Do(add));
Min min = new Min(20, 10);
Console.WriteLine("结果等于:" + c.Do(min));
Mul mul = new Mul(20, 10);
Console.WriteLine("结果等于:" + c.Do(mul));
Div div = new Div(20, 10);
Console.WriteLine("结果等于:" + c.Do(div));
Console.ReadLine();
}
}
///
/// 抽象类,,一个虚方法,,,
///

abstract class Operation
{
public int _a;
public int _b;
public abstract int Op();
}
///
/// 加法类
///

class Add : Operation
{
public Add(int a, int b)
{
this._a = a; //base._a = a;
this._b = b; //base._b = b;
}
public override int Op()
{
return _a + _b;
}
}
///
/// 加法类
///

class Min : Operation
{
public Min(int a, int b)
{
this._a = a;
this._b = b;
}
public override int Op()
{
return _a - _b;
}
}
///
/// 乘法类
///

class Mul : Operation
{
public Mul(int a, int b)
{
this._a = a;
this._b = b;
}
public override int Op()
{
return _a * _b;
}
}
///
/// 除法类
///

class Div : Operation
{
public Div(int a, int b)
{
this._a = a;
this._b = b;
}
public override int Op()
{
return _a / _b;
}
}
///
/// 计算器类,,
///

class Calc
{
public int Do(Operation op)
{
return op.Op();
}
}
}

类图:




分享给朋友:
您可能感兴趣的文章:
随机阅读: