父类与子类的继承、虚方法的使用
来源:互联网 发布:sql select 字段赋值 编辑:程序博客网 时间:2024/06/02 19:10
封装性
父类与子类的继承,在子类没有重写父类的相同的方法时,父类的对象需要强制转换为子类,才可以访问子类中的方法。
但是若子类重写了父类的虚方法,则可以直接调用父类的方法。
体现了虚方法的优势。
在使用虚方法之前
namespace Test_Class{ class Program { static void Main(string[] args) { //练习下父类与子类之间的关系,以及多态性、虚方法的学习 //创建各个对象 Teacher te = new Teacher(); // Test_Class.Teacher.sayHello();//若是定义的teacher类中加static Student1 stu1 = new Student1(); Student2 stu2 = new Student2(); Teacher[] eum = { te,stu1 ,stu2 }; foreach (var item in eum ) { item.sayHello();//这里都是父类对象,所以调用的都是父类的方法; } //若要显示子类方法,需要根据父类中是哪种子类,进行强制转换 foreach (var item in eum) { if (item is Student1) { ((Student1)item).sayHello(); } else if (item is Student2) { ((Student2)item).sayHello(); } else item.sayHello(); } Console.ReadKey(); } } public class Teacher { public void sayHello() { Console.WriteLine("In the class of Teacher"); } } public class Student1:Teacher { public new void sayHello() // 这里添加new,代表将父类中相同的方法彻底隐藏(本来就是隐藏的) { Console.WriteLine ("In the class of student1"); } } public class Student2:Teacher { public new void sayHello() { Console.WriteLine("In the class of student2 "); } }}
使用虚方法后:
namespace Test_Class{ class Program { static void Main(string[] args) { Teacher te = new Teacher(); Student1 stu1 = new Student1(); Student2 stu2 = new Student2(); Teacher[] eum = { te,stu1 ,stu2 }; foreach (var item in eum) //不需要进行强制类型转换,因为子类已经重写了父类中的方法。 { item.sayHello();//这里都是父类对象,但是子类都重写了父类中的虚方法,所以调用的都是各自的方法; } Console.ReadKey(); } } public class Teacher { public virtual void sayHello() { Console.WriteLine("In the class of Teacher"); } } public class Student1:Teacher { public override void sayHello() { Console.WriteLine ("In the class of student1"); } } public class Student2:Teacher { public override void sayHello() { Console.WriteLine("In the class of student2 "); } }}
阅读全文
0 0
- 父类与子类的继承、虚方法的使用
- Java 继承 父类变量, 方法 与子类的关系:
- 子类继承父类的static方法
- 子类继承父类的构造方法
- Java子类与父类的继承
- 继承的顺序,子类覆盖继承父类的方法
- 容器的定义和使用 构造方法 普通方法的调用 查看API及类的继承与子类
- 继承、访问控制符、子类重载父类的方法、子类调用父类的方法
- Java 使用反射观察子类是否继承了父类的私有方法
- 子类继承抽象父类的方法和抽象父类的子类的一些问题
- 子类继承父类的构造函数(方法)吗?
- 子类继承父类的构造函数(方法)吗?
- 子类继承和调用父类的构造方法
- java中,子类能不能继承父类的构造方法?
- PHP规则子类能否继承父类的private方法?
- 子类继承和调用父类的构造方法
- 子类继承和调用父类的构造方法
- js中的子类继承父类的方法和属性
- DiapatcherServlet 源码分析(四)
- 图片垂直居中,小图铺满div,css3点击变红叉,css背景图拉伸铺满
- Dynamic Web Module 3.0 request Java 1.6 or newer---One or more constraints have not been satisfied解决
- gcForest脑电身份识别
- 关于PYTHON NUMPY数组的切片的符号省略问题
- 父类与子类的继承、虚方法的使用
- 二叉搜索树的顺序性
- 浅谈C++重载、重写和隐藏、覆盖
- Netbeans 更改默认语言为英语
- Markdown编辑器使用
- 单向链表的创建、遍历、求长、判存、判空、插入、删除、查找(按位置或元素)、合并
- AUC评价指标
- 百度语音识别和合成SDK for PHP
- Web前段开发路线图