C# 继承
继承是面向对象程序设计中最重要的概念之一。继承允许我们根据一个类来定义另一个类,这使得创建和维护应用程序变得更容易。同时也有利于重用代码和节省开发时间。
当创建一个类时,程序员不需要完全重新编写新的数据成员和成员函数,只需要设计一个新的类,继承了已有的类的成员即可。这个已有的类被称为的基类,这个新的类被称为派生类。
基类和派生类
一个类可以派生自多个类或接口,这意味着它可以从多个基类或接口继承数据和函数
<访问修饰符符> class <基类>
{
...
}
class <派生类> : <基类>
{
...
}
实例
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("继承");
gg hsq = new gg("哈士奇", "灰色", "骨头");
mm bsm = new mm("波斯猫", "白色", "鱼");
Console.ReadKey();
}
}
}
class DongWu
{
private string name { set; get; }
private string color { set; get; }
private string food { set; get; }
public DongWu(string name, string color, string food)
{
this.name = name;
this.food = food;
Console.WriteLine("动物");
}
}
class Gou:DongWu
{
public Gou(string name, string color, string food) : base(name, color, food)
{
Console.WriteLine("狗");
}
}
class Mao : DongWu
{
public Mao(string name, string color, string food) : base(name, color, food)
{
Console.WriteLine("猫");
}
}
class mm:Mao
{
public mm(string name, string color, string food) : base(name, color, food)
{
Console.WriteLine(name + ",白色"+",喜欢吃" + food);
}
}
class gg:Gou
{
public gg(string name, string color, string food) : base(name, color, food)
{
Console.WriteLine(name +",灰色"+ ",喜欢吃" + food);
}
}