• c#抽象类



    抽象类是特殊的类,只是不能被实例化;除此以外,具有类的其他特性;重要的是抽象类可以包括抽象方法,这是普通类所不能的。抽象方法只能声明于抽象类中,且不包含任何实现,派生类必须覆盖它们。另外,抽象类可以派生自一个抽象类,可以覆盖基类抽象方法也可以不覆盖,如果不覆盖,则其派生类必须覆盖它们。
    s比如://抽象形状类
        public abstract class Shaoe
        {
            //定义形状的边
            private int adeg;
            public Shaoe(int adeg)
            {
                this.adeg = adeg;
            }
            //抽象类实现的方法,子类可以重用
            public int GetEdeg()
            {
                return this.adeg;
            }
            //抽象方法,子类必须重写,并在声明上加上override
            public abstract int CalcArea();
        }
        #region
        //三角形类,继承自形状类
        public class Triangle : Shaoe
        {
            private int bottom; //底部
            private int height; //高
            //base就是调用基类的构造函数
            public Triangle(int bottom, int height)
                : base(3)
            {
                this.bottom = bottom;  
                this.height = height;
            }

            //重写方法名
            public override int CalcArea()
            {
                int sum = this.bottom * this.height / 2;
                return sum;
            }
        }
        #endregion
        #region  矩形类,继承自形状类
        //矩形类,继承自形状类
        public class Rectangle : Shaoe
        {
            int bottom;
            int height;
            public Rectangle(int bottom, int height)
                : base(3)
            {
                this.bottom = bottom;
                this.height = height;
            }
            public override int CalcArea()
            {
                int sum = this.bottom * this.height;
                return sum;
            }
        }
        #endregion

            static void Main(string[] args)
            {    //抽象类不能被实例化,父类可以实例化基类继承的抽象类
                Shaoe triangle = new Triangle(4, 5);
                Console.WriteLine(triangle.GetEdeg());
                Console.WriteLine(triangle.CalcArea());
                //抽象基类实例化矩形的类
                Shaoe rectangle = new Rectangle(4, 5);
                Console.WriteLine(rectangle.GetEdeg());
                Console.WriteLine(rectangle.CalcArea());
                Console.ReadLine();
            }





  • 相关阅读:
    带锚点URL同一页面滚动效果的实现
    思路先行
    transliteration -- 2个功能
    html5 section article
    fields('t')
    使用Bootstrap
    JavaScript Switch
    菜单
    写一个博客页面
    自动适应
  • 原文地址:https://www.cnblogs.com/jiaqi/p/3561249.html
Copyright © 2020-2023  润新知