C#程序设计实验--抽象类和派生类

问题

使用抽象类实现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.、完成界面

总结

采用抽象类和派生类是面向对象设计的核心,设计关键在于分析类间的关系和接口。合理的设计能够大大简化编码量,便于日后维护和重用。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值