C#基础知识之类继承
2016-04-21 10:41
609 查看
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ClassInherit { //父类Animal class Animal { //private修饰,它的子类不可以访问 private string _PrivateValue = "private"; //protected修饰,它的子类继承得到 protected int _Weight = 20; //pubic修饰,它的子类继承得到 public int Weight { get { return this._Weight; } set { this._Weight = value; } } //pubic修饰,它的子类继承得到 public void Shout( ) { System.Console.WriteLine("An animal is shouting..."); } } class Dog : Animal { //子类专有,父类没有 private string _Name = "旺财"; //子类专有,父类没有 public string Name { get { return this._Name; } set { this._Name = value; } } //子类专有,父类没有 public void ShowMe() { //子类可以使用从父类继承得到的protected字段:_Name, _Weight System.Console.WriteLine("A dog, name is {0}, and weight is {1} ...", this._Name, this._Weight); } } class Program { static void Main(string[] args) { //创建一个Dog对象 Dog aDog = new Dog( ); //使用Dog从Animal继承得到的属性Weight System.Console.WriteLine("aDog.Name = {0}, aDog.Weight = {1}", aDog.Name, aDog.Weight); //使用Dog专有的成员方法ShowMe() aDog.ShowMe( ); //使用Dog从Animal继承得到的方法Shout() aDog.Shout( ); //Dog是Animal,所以可以讲Dog对象直接赋值到Animal引用 Animal aml = aDog; //使用Animal的成员方法 aml.Shout( ); //aml.ShowMe( ); //错误,因为Animal不能直接访问子类的方法。 ((Dog) aml).ShowMe( );//正确,先强制转换成Dog在使用,因为aml本身就是一个Dog对象。 Animal bAml = new Animal( ); Dog bDog; //bDog = (Dog) bAml; //异常,因为bAml实际上不是Dog对象 bDog = (Dog) aml; //正确,因为aml本身就是一个Dog对象 System.Console.WriteLine("aml is Animal : {0}", aml is Animal); System.Console.WriteLine("aml is Dog : {0}", aml is Dog); System.Console.WriteLine("bAml is Animal : {0}", bAml is Animal); System.Console.WriteLine("bAml is Dog : {0}", bAml is Dog); } } }
注释的很清楚,这里就不累赘啦,加油!关于C#,C++细节里的那些疑难杂症请访问geeksforgeeks官网(http://www.geeksforgeeks.org/)
相关文章推荐
- Android Native 绘图方法
- PostgreSQL教程(三):表的继承和分区表详解
- C#中struct和class的区别详解
- Lua面向对象之类和继承浅析
- 浅析Ruby中继承和消息的相关知识
- VBS ArrayList Class vbs中的数组类
- 大家看了就明白了css样式中类class与标识id选择符的区别小结
- 设计引导--一个鸭子游戏引发的设计理念(多态,继承,抽象,接口,策略者模式)
- C++实现不能被继承的类实例分析
- C# 面向对象三大特性:封装、继承、多态
- PHP类的封装与继承详解
- 深入了解PHP类Class的概念
- js继承 Base类的源码解析
- jquery 表单验证之通过 class验证表单不为空
- Javascript 面向对象 继承
- JavaScript 继承使用分析
- Javascript面向对象编程(二) 构造函数的继承
- Javascript中的几种继承方式对比分析
- javascript面向对象之Javascript 继承
- JavaScript 对象、函数和继承