您的位置:首页 > 编程语言 > C#

C# 继承

2016-09-13 20:31 155 查看
C# 继承

 

简介:继承是面向对象的程序设计语言,它是在类之间建立的一种相交关系,且可以加入和修改已有的特性,还可以根据一个类来定义另一个类,是我们更容易创建和维护应用程序,也可一减少重用代码,节省代码开发的时间。

概括:当创建类是不需要重新写,只需设计一个新的类,继承已有的类的成员。一个类可以派生多个类或接口

目的:为了提高软件模块的可复用性和可扩充性,提高软件的开发效率,使代码的灵活性更强。派生类继承类基类的成员变量和方法。

解决问题:减少了代码的重复率,提高了代码效率。

代码:

 

   class Rectangle

   {

      // 成员变量

      protected double length;

      protected double width;

      public Rectangle(double l, double w)

      {

         length = l;

         width = w;

      }

      public double GetArea()

      {

         return length * width;

      }

      public void Display()

      {

         Console.WriteLine("长度: {0}", length);

         Console.WriteLine("宽度: {0}", width);

         Console.WriteLine("面积: {0}", GetArea());

      }

   }//end class Rectangle  

   class Tabletop : Rectangle

   {

      private double cost;

      public Tabletop(double l, double w) : base(l, w)

      { }

      public double GetCost()

      {

         double cost;

         cost = GetArea() * 70;

         return cost;

      }

      public void Display()

      {

         base.Display();

         Console.WriteLine("成本: {0}", GetCost());

      }

   }

   class ExecuteRectangle

   {

      static void Main(string[] args)

      {

         Tabletop t = new Tabletop(4.5, 7.5);

         t.Display();

         Console.ReadLine();

      }

   }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: