C#中的繼承舉例
阿新 • • 發佈:2019-02-08
原始碼:
using System; namespace Inherit { public class Person { public string name; //定義域 public int age; virtual public void SayHello() { //定義方法 //virtual表示可以被子類override Console.WriteLine("Hello! My name is " + name); } public void SayHello(Person another) { //構造方法過載同名的sayHello方法 Console.WriteLine("Hello," + another.name + "! My name is " + name); } public bool IsOlderThan(int anAge) { //定義方法 bool flg; if (age > anAge) flg = true; else flg = false; return flg; } public Person(string n, int a) { //構造方法 name = n; age = a; } public Person(string n) { //構造方法過載 name = n; age = -1; } public Person() : this("", 0)//呼叫其他構造方法 { } } public class Student : Person //定義子類 { public string school; //增加的欄位 public int score = 0; public bool isGoodStudent() { //增加的方法 return score >= 90; } override public void SayHello() { //override覆蓋父類的方法 base.SayHello(); Console.WriteLine("My school is " + school); } public void SayHello(Student another) { //增加的方法 Console.WriteLine("Hi!"); if (school == another.school) Console.WriteLine(" Shoolmates "); } public Student() { //構造方法 } public Student(string name, int age, string school) : base(name, age) //呼叫父類的構造方法 { this.school = school; } public void TestThisSuper() { int a; a = age; //本句與以下兩句效果相同 a = this.age; //使用this a = base.age; //使用base } } class Program { static void Main(string[] args) { Person p = new Person("Liming", 50); Student s = new Student("Wangqiang", 20, "PKU"); Person p2 = new Student("Zhangyi", 18, "THU"); Student s2 = (Student)p2; //型別轉換 } } }