码迷,mamicode.com
首页 > 其他好文 > 详细

类的继承,方法的重载和覆写

时间:2015-07-04 18:19:26      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

在网易云课堂上看到唐大仕老师讲解的关于类的继承、方法的重载和覆写的一段代码,注释比较详细,在此记下以加深理解。

小总结:

1、类的继承:同类可以实例化(Student t=new Student(),Person p=new Person()),人类可以强制转换为学生类(Student t=(Student)Person),人类可以是学生类(Person p=new Student());

2、方法的重载:只要求方法名称相同,返回类型、参数数目和参数类型都可以不相同;

3、方法的覆写:只有基类中有virtural修饰的方法才可以在子类中覆写,如果子类覆写了一个基类的方法,那么子类调用该方法实际上调用的是子类被覆写后的方法。如果在基类中该方法有重载的其他方法,那么子类中调用该方法名称时会提示有重载方法,此时根据函数的参数来确定具体调用的是基类还是子类的方法,返回类型也与调用的具体的方法定义有关。

 1 using System;
 2 public class Person {
 3     public string name; //定义域
 4     public int age;
 5     virtual public void SayHello(){ //定义方法 //virtual表示可以被子类override
 6         Console.WriteLine("Hello!  My name is " + name );
 7     }
 8     public void SayHello( Person another ){  //构造方法重载同名的sayHello方法
 9         Console.WriteLine("Hello," + another.name + 
10             "! My name is " + name );
11     }
12     public bool IsOlderThan( int anAge ){ //定义方法
13         bool flg;
14         if( age > anAge ) flg = true; else flg=false;
15         return flg;
16     }
17     public Person( string n, int a ){ //构造方法
18         name = n;
19         age = a;
20     }
21     public Person( string n ){ //构造方法重载
22         name = n;
23         age = -1;
24     }
25     public Person(  ):this(  "", 0 )//调用其他构造方法
26     { 
27     }
28 }
29  
30 public class  Student : Person  //定义子类
31 {
32     public string school; //增加的字段
33     public int score = 0;
34     public bool isGoodStudent(){ //增加的方法
35         return score>=90;
36     }
37     override public void SayHello(){ //override覆盖父类的方法
38         base.sayHello();
39         Console.WriteLine( "My school is " + school );
40     }
41     public void SayHello( Student another ){ //增加的方法
42         Console.WriteLine("Hi!");
43         if( school == another.school ) 
44             Console.WriteLine(" Shoolmates ");
45     }
46  
47     public Student(){  //构造方法
48     }
49     public Student(string name, int age, string school ) 
50         : base( name, age ) //调用父类的构造方法
51     {
52         this.school = school;
53     }
54      
55     public void TestThisSuper(){
56         int a;
57         a = age;      //本句与以下两句效果相同
58         a = this.age; //使用this
59         a = base.age; //使用base
60     }
61  
62  
63     public static void Main( string [] arggs )
64     {
65         Person p = new Person( "Liming", 50 );
66         Student s = new Student( "Wangqiang", 20, "PKU" );
67         Person p2 = new Student( "Zhangyi", 18, "THU" );
68         Student s2 = (Student) p2; //类型转换
69     }
70 }

 

类的继承,方法的重载和覆写

标签:

原文地址:http://www.cnblogs.com/mzyj/p/4620957.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!