首页 技术 正文
技术 2022年11月22日
0 收藏 924 点赞 4,130 浏览 1446 个字
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;/*
简单说,抽象方法是需要子类去实现的。虚方法是已经实现了的,可以被子类覆盖,也可以不覆盖,取决于需求。抽象方法和虚方法都可以供派生类重写。
*/
namespace MySpace
{
class dad
{
protected string name; //成员变量 public dad(string n) //构造函数
{
name = n;
}
public void say() //基类say方法
{
Console.WriteLine("I am {0}.", name);
}
public virtual void growup() //基类growup方法 虚函数
{
Console.WriteLine("{0} has grown old.", name);
}
}
class son : dad //继承父亲
{
public son(string n) //构造函数
: base(n)
{
//name = n;
}
public new void say() //在派生类中定义的和基类中的某个方法同名的方法,使用 new 关键字定义
{
Console.WriteLine("I am {0} and a son.", name);
}
public override void growup() //重写(override)是用于重写基类的虚方法,这样在派生类中提供一个新的方法,继承类中的重写虚函数需要声明关键字 override
{
//base.growup();
Console.WriteLine("{0} is growing up.", name);
}
}
class entrance
{
public static void Main()
{
dad grandpa = new dad("grandpa"); //用父类生成的父类对象
grandpa.say(); //父类say方法的调用
grandpa.growup(); //父类growup方法的调用 Console.WriteLine("\nnew son(\"father\")");
dad father = new son("father"); //用子类生成的父类对象
father.say(); //调用父类方法,访问隐藏方法是父类的方法
father.growup(); //调用子类方法,访问重写方法是子类的方法 Console.WriteLine("\nson tom = new son(\"Tom\")");
son tom = new son("Tom"); //用子类生成的子类对象
tom.say(); //访问隐藏方法是子类的方法,访问重写方法是子类的方法
tom.growup(); //Console.ReadKey();
}
}
}/*I am grandpa.
grandpa has grown old.new son("father")
I am father.
father is growing up.son tom = new son("Tom")
I am Tom and a son.
Tom is growing up.
*
* 上边的结果: 1)用父类生成的父类对象,grandpa,访问隐藏方法是父类的方法,访问重写方法是父类的方法
2)用子类生成的父类对象,father,访问隐藏方法是父类的方法,访问重写方法是子类的方法
3)用子类生成的子类对象,son,访问隐藏方法是子类的方法,访问重写方法是子类的方法
请按任意键继续. . .
*/

  这个实例比较好,因此特此转载。说明了new和override的区别。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,484
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,899
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,732
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,485
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,125
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,285