问题
使用抽象类实现shape,抽象类包含两个接口面积和周长。并用virtual和override实现rectangle和square类
解析
1 如图存在两种实现,
(
1)长方形与正方形直接派生
(2) 正方形派生长方形, 长方形派生Shape
(2)的设计要比(1)更好,因为它是对真实世界的反映,代码更简洁。
2、创建抽象类Shape
abstract class Shape
{
public abstract double Perimeter();
public abstract double Area();
}
3、实现派生类Rectangle
class Rectangle : Shape
{
protected double length;
protected double width;
public Rectangle(double length, double width)
{
this.length = length;
this.width = width;
}
public Rectangle(double a)
{
this.length = this.width = a;
}
public Rectangle()
{
this.length = this.width = 0;
}
public override double Perimeter()
{
return (this.length + this.width) * 2;
}
public override double Area()
{
return this.length * this.width;
}
}
4、实现派生类Square
class Square : Rectangle
{
public Square(double a)
{
this.length = this.width = a;
}
}
注意
Rectangle需要提供一个默认构造函数和含一个参数的构造函数,这是因为Square的构造函数需要。
完整控制台程序如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Shape
{
abstract class Shape
{
public abstract double Perimeter();
public abstract double Area();
}
class Rectangle : Shape
{
protected double length;
protected double width;
public Rectangle(double length, double width)
{
this.length = length;
this.width = width;
}
public Rectangle(double a)
{
this.length = this.width = a;
}
public Rectangle()
{
this.length = this.width = 0;
}
public override double Perimeter()
{
return (this.length + this.width) * 2;
}
public override double Area()
{
return this.length * this.width;
}
}
class Square : Rectangle
{
public Square(double a)
{
this.length = this.width = a;
}
}
class Program
{
static void Main(string[] args)
{
Square s = new Square(12);
Console.WriteLine("面积为:"+s.Area());
}
}
}
5.、完成界面
总结
采用抽象类和派生类是面向对象设计的核心,设计关键在于分析类间的关系和接口。合理的设计能够大大简化编码量,便于日后维护和重用。