继承

//c#中任何一个类都是继承自object类的。

//如果一个类没有显示继承自任何类,则默认继承自object类。
 //如果显示的指定了当前类继承自某个类,则将覆盖默认继承的object类。//===继承的传递性:
 //SuperMan继承了object,这时,SuperMan类中就有了从object类中继承下来的4个方法ToString()、GetType()、GetHashCode()、Equals()。
//然后Person又继承了SuperMan,这时,Person会将SuperMan中的那4个方法再继承下来。由于那4个方法是在object中的,所以相当于Person类间接从Object类中继承下来了成员
 //这个就叫继承的传递性。

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace _05继承中的构造函数问题
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             Student stu = new Student("张三", 18, 100);
13             Console.WriteLine(stu.Name);
14             Console.WriteLine(stu.Age);
15             Console.WriteLine(stu.Score);
16             Console.ReadKey();
17 
18         }
19     }
20     class Person
21     {
22         ////修正错误方法1:在父类中增加一个无参数的构造函数。
23         ////这时子类的构造函数就可以找到父类中的无参构造函数了。
24         public Person()
25         {
26             Console.WriteLine("Person类中的无参数的构造函数。。。。");
27         }
28 
29         public Person(string name, int age)
30         {
31             this.Name = name;
32             this.Age = age;
33         }
34 
35         public Person(string name)
36         {
37             this.Name = name;
38             this.Age = 0;
39         }
40 
41         public string Name
42         {
43             get;
44             set;
45         }
46         public int Age
47         {
48             get;
49             set;
50         }
51     }
52     //1.继承的时候,构造函数不能被继承。
53     //2.字类的构造函数会默认去调用父类中的无参数的构造函数
54     class Student : Person
55     {
56 
57         //修正错误方法2:不修改父类,而是在子类的构造函数后面通过:base(),显示的去调用父类的某个构造函数。
58         public Student(string name, int age, double score)
59             : base(name, age) //base的作用1:在子类中调用父类的构造函数。
60         {
61             // this.Name = name;
62             //this.Age = age;
63             this.Score = score;
64         }
65         public double Score
66         {
67             get;
68             set;
69         }
70     }
71     class Teacher : Person
72     {
73         public Teacher(string name, int age, double salary)
74             : base(name)
75         {
76             //this.Name = name;
77             this.Age = age;
78             this.Salary = salary;
79         }
80         public double Salary
81         {
82             get;
83             set;
84         }
85     }
86 }
构造函数的继承

 

posted @ 2013-07-17 18:53  墓地de小草  阅读(197)  评论(0编辑  收藏  举报