Chapter 8. 面向对象(继承)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 继承 { public class Person { //字段 private string _name; private int _age; private char _gender; //属性 public string Name { get { return _name; } set { _name = value; } } public int Age { get { return _age; } set { _age = value; } } public char Gender { get { return _gender; } set { _gender = value; } } //方法 public void Say() { Console.WriteLine ("我是"+this.Name+",我"+this.Age+"岁了"+",我是"+this.Gender+"性,我会吃喝拉撒睡"); } } public class Student : Person //Student继承Person { private int _id; public int Id { get { return _id; } set { _id = value; } } public void Study() { Console.WriteLine("我会学习"); } } public class Teacher : Student //Teacher继承Student { private decimal _salaray; public decimal Salaray { get { return _salaray; } set { _salaray = value; } } public void Teach() { Console.WriteLine("我会教课"); } } public class Professor : Teacher //Professor继承Teacher { private int _teachTime; public int TeachTime { get { return _teachTime; } set { _teachTime = value; } } public void Profess() { Console.WriteLine("我是教授"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 继承 { class Program { static void Main(string[] args) { //Person类 Person pp = new Person(); pp.Name = "人"; pp.Age = 0; pp.Gender='无'; pp.Say();
//Student类继承了Person类的所有属性和方法 Student s = new Student(); s.Name = "张三"; s.Age = 18; s.Gender = '男'; s.Id = 1001; s.Say(); s.Study();
//Teacher类继承了Person和Student类的所有属性和方法 Teacher t = new Teacher(); t.Name = "李四"; t.Age = 25; t.Gender = '女'; t.Id = 2001; t.Say(); t.Study(); t.Salaray = 5000.00M; t.Teach();
//Driver类继承了Person和Student和Teacher类的所有属性和方法 Professor p = new Professor(); p.Name = "王五"; p.Age = 35; p.Gender = '男'; p.Id = 3001; p.Say(); p.Study(); p.Salaray = 10000.00M; p.Teach(); p.TeachTime = 3; p.Profess();
Console.ReadLine(); } } }