父类与子类的继承、虚方法的使用

来源:互联网 发布: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
原创粉丝点击