设计模式拓展——继承

本文深入探讨了面向对象编程中的继承概念,解释了继承如何通过实现IS-A关系,允许新类复用现有类的数据成员和成员函数,从而提高代码效率和可维护性。文章通过具体示例展示了继承的语法和用法,包括单继承和多重继承(通过接口实现),并演示了如何在实际项目中运用继承来优化代码结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.什么是继承

2.继承有什么用

3.怎么用继承

概念:当创建一个类时,程序员不需要完全重新编写新的数据成员和成员函数,只需要设计一个新的类,继承了已有的类的成员即可,这个已有类被称为的基类,这个新的类被称为派生类
继承的思想实现了属于(IS-A)关系。例如,哺乳

物属于(IS-A)动物,够属于(IS-A)哺乳动物,一次狗属于(IS-A)动物
继承有什么用:当创建一个类时,程序员不需要完全重新编写新的数据成员和成员函数,只需要设计一个新的类,继承了已有的类的成员即可,这个已有类被称为的基类,这个新的类被称为派生类.

怎么用继承

//语法
<访问修饰符符> class <基类>
{
 ...
}
class <派生类> : <基类>
{
 ...
}

多重继承(c#不支持多重继承,要多重继承请使用接口)

using System;
namespace InheritanceApplication
{
   class Shape
   {
      public void setWidth(int w)
      {
         width = w;
      }
      public void setHeight(int h)
      {
         height = h;
      }
      protected int width;
      protected int height;
   }

   // 基类 PaintCost
   public interface PaintCost
   {
      int getCost(int area);

   }
   // 派生类
   class Rectangle : Shape, PaintCost
   {
      public int getArea()
      {
         return (width * height);
      }
      public int getCost(int area)
      {
         return area * 70;
      }
   }
   class RectangleTester
   {
      static void Main(string[] args)
      {
         Rectangle Rect = new Rectangle();
         int area;
         Rect.setWidth(5);
         Rect.setHeight(7);
         area = Rect.getArea();
         // 打印对象的面积
         Console.WriteLine("总面积: {0}",  Rect.getArea());
         Console.WriteLine("油漆总成本: ${0}" , Rect.getCost(area));
         Console.ReadKey();
      }
   }
}

tip:

using System;
namespace InheritanceApplication
{
   class Shape
   {
      public void setWidth(int w)
      {
         width = w;
      }
      public void setHeight(int h)
      {
         height = h;
      }
      protected int width;
      protected int height;
   }

   
   // 派生类
   class Rectangle : Shape
   {
      public int getArea()
      {
         return (width * height);
      }
      public int getCost(int area)
      {
         return area * 70;
      }
   }
   class RectangleTester
   {
      static void Main(string[] args)
      {
         Shape Rect = new Rectangle();//--------若使用单继承则可用变量名前面可以基类名,若多重继承则只能用new出来的类型
         int area;
         Rect.setWidth(5);
         Rect.setHeight(7);
        // area = Rect.getArea();
         // 打印对象的面积
      //   Console.WriteLine("总面积: {0}",  Rect.getArea());
      //   Console.WriteLine("油漆总成本: ${0}" , Rect.getCost(area));
         Console.ReadKey();
      }
   }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值