C# 继承的实现
//创建一个Person的父类
public class Person
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
private string _gender;
public string Gender
{
get { return _gender; }
set { _gender = value; }
}
public Person(string name, int age, string gender)
{
this.Name = name;
this.Age = age;
this.Gender = gender;
}
}
//创建一个Student的子类
public class Student : Person
{
private int _number;
public int Number
{
get { return _number; }
set { _number = value; }
}
public Student(string name,int age,string gender, int number):base(name,age,gender)
{
//因为父类是一个以后参数的,所以子类后面要加base
//通过上面的构造函数给子类的构造函数赋值,就可以调用父类的方法
this.Number = number;
}
public void ShowStudent()
{
Console.WriteLine("{0},{1},{2},{3}", Name, Gender, Age, Number);
}
}
//创建一个Teacher的子类
public class Teacher : Person
{
public Teacher(string name, int age, string gender) : base(name, age, gender)
public void ShowTeacher()
{
Console.Write("{0},{1},{2}", Name, Age, Gender);
}
public void Teach()
{
Console.WriteLine("我再教C#");
}
}
//创建类的实例对象
static void Main(string[] args)
{
//子类对付类的扩展,也可以添加新的成员,但是不能移除已有的继承成员
//继承是可以传递的,c继承B,B继承A,C不但继承B也继承A
//继承了属性和方法,私有子段没有被继承
//子类如果定义了与父类成员名相同的成员,那么就可以覆盖掉父类的成员,并不是删除只是无法访问父类成员
//单根性 传递性
Student s1 = new Student("吴彦祖", 18, "男", 666);
s1.ShowStudent();
Teacher t1 = new Teacher("帅哥", 22, "男");
t1.ShowTeacher();
t1.Teach();
}