C#学习日记22---多重继承
2015-10-12 18:44
447 查看
继承是面向对象程序设计中最重要的概念之一。继承允许我们根据一个类来定义另一个类来定义一个类,一个类从另一个类派生出来时,派生类从基类那里继承特性
继承的思想实现了 属于(IS-A) 关系。例如,哺乳动物
属于(IS-A) 动物,狗 属于(IS-A) 哺乳动物,因此狗 属于(IS-A) 动物。
下面写个实例。
结果:
继承的思想实现了 属于(IS-A) 关系。例如,哺乳动物
属于(IS-A) 动物,狗 属于(IS-A) 哺乳动物,因此狗 属于(IS-A) 动物。
基类与派生类:
C#中派生类从他的直接基类继承成员,方法、属性、域、事件、索引指示器但是除开构造函数与析构函数。下面写个实例。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test { class Anlimal //定义一个基类 { protected int foot = 4; protected double weight = 22.4; protected void say(string type, string call) { Console.WriteLine("类别:{0},叫声:{1} ",type,call); } } //Dog 继承Anlimal class Dog:Anlimal { static void Main(string[] args) { Dog dog = new Dog(); int foot = dog.foot; double weight = dog.weight; Console.WriteLine("dog foot: {0}\ndog weight:{1}",foot,weight); dog.say("狗", "汪汪"); } } }
结果:
多重继承:
C# 不支持多重继承。但是,您可以使用接口来实现多重继承,上面的例子我们为他添加一个smallanlimal接口using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test { class Anlimal //定义一个基类 { protected int foot = 4; protected double weight = 22.4; protected void say(string type, string call) { Console.WriteLine("类别:{0},叫声:{1} ",type,call); } } public interface smallanlimal //添加一个接口 接口只声明方法在子类中实现 { protected void hight(double hight); } //Dog 继承Anlimal class Dog:Anlimal,smallanlimal { public void hight(double hight) //实现接口 { Console.WriteLine("Hight: {0}",hight); } static void Main(string[] args) { Dog dog = new Dog(); int foot = dog.foot; double weight = dog.weight; dog.hight(23.23); Console.WriteLine("dog foot: {0}\ndog weight:{1}",foot,weight); dog.say("狗", "汪汪"); } } }
相关文章推荐
- MySQL中的integer 数据类型
- Android Native 绘图方法
- c#调用COM组件
- MySQL 数据类型
- C#实现把指定数据写入串口
- C#动态创建button的方法
- C#中抽象方法与虚拟方法的区别
- c#中虚函数的相关使用方法
- C#使用加边法计算行列式的值
- C#实现多线程的同步方法实例分析
- C#中尾递归的使用、优化及编译器优化
- PostgreSQL教程(三):表的继承和分区表详解
- C#实现子窗体与父窗体通信方法实例总结
- C#通用邮件发送类分享
- PostgreSQL教程(四):数据类型详解
- C#中this的用法集锦
- C#.NET获取拨号连接的宽带连接方法
- C#异步绑定数据实现方法
- C#实现AddRange为数组添加多个元素的方法
- C#中Equality和Identity浅析