本帖最后由 一片白 于 2014-5-10 14:24 编辑
一、抽象类实现
using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace _27 { class Program { static void Main(string[] args) { //圆形 Shape shape1 = new Circle(3.0); Console.WriteLine("面积是:" + shape1.CalculateArea()); Console.WriteLine("周长是:" + shape1.CalculatePerimeter()); //矩形 Shape shape2 = new Retangle(4, 7.3); Console.WriteLine("面积是:" + shape2.CalculateArea()); Console.WriteLine("周长是:" + shape2.CalculatePerimeter()); Console.ReadKey(); } }
//抽象类 Shape abstract class Shape { public double Area { get; set; } //面积属性 public double Perimeter { get; set; } //周长
public abstract double CalculateArea();//计算面积的方法 public abstract double CalculatePerimeter();//计算周长 }
//圆形 class Circle : Shape { //属性:半径 public double r { get; set; } //构造函数 public Circle(double r) { this.r = r; } //重写 计算面积的方法 public override double CalculateArea() { this.Area = Math.PI * r * r; return this.Area; }
public override double CalculatePerimeter() { this.Perimeter = 2 * Math.PI * r; return this.Perimeter; } } //矩形 class Retangle : Shape { public double height { get; set; } public double width { get; set; }
//构造函数 public Retangle(double height, double width) { this.height = height; this.width = width; }
public override double CalculateArea() { this.Area = height * width; return this.Area; }
public override double CalculatePerimeter() { this.Perimeter = (height + width) * 2; return this.Perimeter; } }
}
二、接口实现 using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace _27_2 { class Program { static void Main(string[] args) { ICalculateArea area1 = new Circle(3); ICalculateArea area2 = new Retangle(2, 3.33); Console.WriteLine("area1的面积是" + area1.CalculateArea()); Console.WriteLine("area2的面积是" + area2.CalculateArea());
ICalculatePerimeter p1 = new Circle(3); ICalculatePerimeter p2 = new Retangle(2, 3.33); Console.WriteLine("area1的周长是" + p1.CalculatePerimeter()); Console.WriteLine("area2的周长是" + p2.CalculatePerimeter());
Console.ReadKey(); } }
//接口 面积 interface ICalculateArea { double CalculateArea(); } //接口 周长 interface ICalculatePerimeter { double CalculatePerimeter(); }
//圆形 class Circle : ICalculateArea, ICalculatePerimeter { //属性:半径 public double r { get; set; } //构造函数 public Circle(double r) { this.r = r; }
public double CalculateArea() { return Math.PI * r * r; }
public double CalculatePerimeter() { return 2 * Math.PI * r; } } //矩形 class Retangle : ICalculateArea, ICalculatePerimeter { public double height { get; set; } public double width { get; set; } //构造函数 public Retangle(double height, double width) { this.height = height; this.width = width; }
public double CalculateArea() { return height * width; }
public double CalculatePerimeter() { return (height + width) * 2; } } }
{:3_51:}自己的见解,也不知道是否完全正确。
黑马朋友,共同学习!
|