1.先写一个形状的抽象类,和获取面积,周长的抽象方法
public abstract class Shape
{
public abstract double GetArea();
public abstract double GetPerimter();
}
2.写个圆形的类,继承形状类,弄个私有属性半径r,重写获取面积周长的方法
public class Circle:Shape
{
private double _r;
public double R
{
get
{
return _r;
}
set
{
_r = value;
}
}
public Circle(double r)
{
this.R = r;
}
public override double GetArea()
{
return Math.PI * this.R * this.R;
}
public override double GetPerimter()
{
return Math.PI * 2 * this.R;
}
}
3.写个矩形的类,继承形状类,私有属性长和宽,重写获取面积周长的方法
public class Square:Shape
{
private double _height;
private double _width;
public double Height
{
get
{
return _height;
}
set
{
_height = value;
}
}
public double Width
{
get
{
return _width;
}
set
{
_width = value;
}
}
public Square(double height,double width)
{
this.Height = height;
this.Width = width;
}
public override double GetArea()
{
return this.Width * this.Height;
}
public override double GetPerimter()
{
return 2 * this.Width * this.Height;
}
}
4.实现调用
class Program
{
static void Main(string[] args)
{
//使用多态求矩形的面积和周长,求圆形的面积和周长
Shape shape = new Circle(5);
double Area = shape.GetArea();
double Perimter = shape.GetPerimter();
Console.WriteLine(\”周长是{0},面积是{1}\”, Perimter, Area);
Shape shape2 = new Square(5,4);
Area = shape2.GetPerimter();
Perimter = shape2.GetArea();
Console.WriteLine(\”周长是{0},面积是{1}\”, Perimter, Area);
Console.ReadLine();
}
}