设计一个 Shape类和它的三个子类Square、Rectangle和Circle,并进行测试。
提示:
(1)Shape类中有一个方法Area(),该方法接收一个double类型的参数,返回一个double类型的结果。
(2)三个子类中实现了Shape父类的Area()方法,分别求正方形、长方形和圆形的面积并返回。
(3)在测试类中创建Square对象、Rectangle对象和Circle对象,计算边长为2的正方形面积、长为3宽为2的长方形面积和半径为3的圆形面积。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Shape
{
public virtual double Area(double num)
{
return 0;
}
}
class Square : Shape
{
private double side;
public Square (double side)
{
this.side = side;
}
public override double Area(double num = 0)
{
return side * side;
}
}
class Rectangle:Shape
{
private double length;
private double width;
public Rectangle(double length,double width)
{
this.length = length;
this.width = width;
}
public override double Area(double num=0)
{
return length*width;
}
}
class Circle:Shape
{
private double radius;
public Circle (double radius)
{
this.radius = radius;
}
public override double Area(double num=0)
{
return 3.14*radius*radius;
}
}
internal class Program
{
static void Main(string[] args)
{
Square square = new Square(2);
Rectangle rectangle = new Rectangle(3, 2);
Circle circle = new Circle(3);
Console.WriteLine("正方形面积:" + square.Area());
Console.WriteLine("长方形面积:" + rectangle.Area());
Console.WriteLine("圆形面积:" + circle.Area());
Console.ReadKey();
}
}
}