C#基础知识之类继承
来源:互联网 发布:dw如何连接动态数据 编辑:程序博客网 时间:2024/05/20 17:27
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/)
0 0
- C#基础知识之类继承
- Java基础知识总结之类的继承
- C#之类继承,接口学习案例
- C#基础知识整理:基础知识(4) 继承
- C#之类
- c#之类
- java基础之类继承
- java基础之类继承
- C++之类继承
- OC之类的继承
- Code First 之类继承
- C++之类的继承
- c++学习之类继承
- swift之类的继承
- Java之类的继承
- C++之类的继承
- oc基础知识之类的定义
- python基础知识之类和文件
- C++作业4
- 在幼儿园管理系统中,批量导入(file)想美化成一个按钮来实现。
- iOS内存优化集合一
- 第一次作业-加锁
- 217. Contains Duplicate
- C#基础知识之类继承
- 魔方系列——最小装箱
- Spring事务管理—AOP/Annotation
- C++第四次实验—利用循环求和
- webview加载图片
- 关于http协议在windos 的vs下面正常运行,在Mac下的xcode运行不报错,但不成功的问题
- java 非对称加密小例子
- 论文摘要要多少字合适
- php调用系统命令