我们可能会在一些类中,写一些重复的成员,我们可以将这些重复的成员,单独的封装到一个类中,作为这些类的父亲。
Student Teacher Driver 子类 派生类
Person 父类 基类
子类继承了父类的属性和方法,但是子类并没有继承父类的私有字段。
子类并有没继承父类的构造函数。但是子类会默认的调用父类无参数的构造函数,创建父类对象,让子类可以使用父类中的成员。
所以在父类中重新写了一个有参数的构造函数之后,那个无参数的就被干掉了,子类就调用不到了。
解决方法:
1、在父类中重新写一个无参数的构造函数。
2、在子类中显示的调用父类的构造函数,使用关键字:base()
public test(sting s):base(s)——->把s这个参数传给父类的构造函数。
—————————————————继承的特性———————————————————
1、单根性
2、传递性
using System;
namespace _059_面对对象继承_05_继承
{
class Program
{
static void Main(string[] args)
{
Student student = new Student("老六", 18, '男', 10086);
student.Study();
Console.WriteLine("我的名字是:{0},今年{1}岁了,是个{2}生,我的编号是{3}", student.Name, student.Age, student.Gender, student.Id);
Console.ReadKey();
}
}
}
class Person
{
public Person(string name,int age,char gender)
{
this.Name = name;
this.Age = age;
this.Gender = gender;
}
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 char _gender;
public char Gender
{
get { return _gender; }
set { _gender = value; }
}
}
class Student : Person
{
public Student(string name, int age, char gender, int id) : base(name, age, gender)
{
//this.Name = name;
//this.Age = age;
//this.Gender = gender;
this.Id = id;
}
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
public void Study()
{
Console.WriteLine("学习");
}
}
class Teacher:Person
{
public Teacher(string name, int age, char gender, double salary) : base(name, age, gender)
{
//this.Name = name;
//this.Age = age;
//this.Gender = gender;
this.Salary = salary;
}
private double _salary;
public double Salary
{
get { return _salary; }
set { _salary = value; }
}
public void Teach()
{
Console.WriteLine("讲课");
}
}
class Driver:Person
{
public Driver(string name, int age, char gender, int driveTime) : base(name, age, gender)
{
//this.Name = name;
//this.Age = age;
//this.Gender = gender;
this.DriveTime = driveTime;
}
private int _driveTime;
public int DriveTime
{
get { return _driveTime; }
set { _driveTime = value; }
}
public void Drive()
{
Console.WriteLine("开车");
}
}