C# 类的继承

类的继承

using System;

namespace MyNameSpace {
    class Attributes {
        protected double length;
        protected double width;
        // 带参数的构造函数,类实例化的时候就需要传入
        public Attributes(double length, double width)
        {
            this.length = length;
            this.width = width;
        }

        // 计算面积的公共方法
        public double getArea() { 
            return length * width;
        }
    }

    // Price类继承自Attributes类,Attributes为基类,Price为派生类(指基于哪个类衍生的类叫做派生类)
    class Price : Attributes { 
	
        private double cost;

        // 当基类中含有带参数的构造函数,那么就要加上base并带上参数,如果不加base那么默认走不带参数的构造函数。
        public Price(double length, double width): base(length, width) { }
		
        public double getCost() {
            // 由于该类继承自Attributes类,那么可以直接调用Attributes类中的getArea方法。
            this.cost = getArea() * 70;
            return this.cost;
        }
    }

    class MyMain { 
        static void Main(string[] args)
        {
            var p = new Price(4.1, 8.8);
            Console.WriteLine(p.getCost());
            
        }
    }
}
posted @ 2022-12-22 09:23  枸杞泡茶呀  阅读(51)  评论(0)    收藏  举报