C#基础-面向对象-继承
继承
新建一个基类
对Person类3个字段进行重构->封装字段
效果如下:
public string Name { get => name; set => name = value; }
public string Sex { get => sex; set => sex = value; }
public int Age { get => age; set => age = value; }
完整Person类代码
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp6
{
// 作为被继承的,称为基类,也称为父类
public class Person
{
private string name;
private string sex;
private int age;
public Person()
{
}
public Person(string _name, string _sex, int _age)
{
this.name = _name;
this.sex = _sex;
this.age = _age;
}
public string Name { get => name; set => name = value; }
public string Sex { get => sex; set => sex = value; }
public int Age {
get { return age; }
set {
if (value <= 0)
{
age = 12;
}
else
{
age = value;
}
}
}
}
}
新建一个Doctor类,继承Person
继承的称为子类,或派生类,从person中继承了非private的属性
// 称为派生类,也称为子类,继承Person
public class Doctor:Person
{
}
主函数调用Doctor属性
class Program
{
static void Main(string[] args)
{
Doctor d = new Doctor();
d.Name = "James";
d.Sex = "Male";
d.Age = 23;
Console.WriteLine("医生姓名:{0},性别:{1},年龄:{2}。", d.Name, d.Sex, d.Age);
}
}
子类的构造函数继承父类,并在父类基础上有所增加
// 称为派生类,也称为子类,继承Person
public class Doctor:Person
{
private string departName;
//base 表示调用父类
public Doctor(string _name,string _sex,int _age,string _departName) : base(_name, _sex, _age) // 调用父类的构造函数
{
this.DepartName = _departName;
}
public string DepartName { get => departName; set => departName = value; }
}
主函数实现效果:
static void Main(string[] args)
{
Doctor d = new Doctor("jake","male",24,"外科");
Console.WriteLine("医生姓名:{0},性别:{1},年龄:{2},科室:{3}。", d.Name, d.Sex, d.Age, d.DepartName);
}
new与override
子类覆盖父类的方法,使用new关键字
public class Person
{
public void ShowInfo()
{
Console.WriteLine("Person类的ShowInfo方法");
}
}
子类覆盖父类的方法,使用new关键字
// 称为派生类,也称为子类,继承Person
public class Doctor:Person
{
// 子类覆盖父类的方法,使用new关键字
public new void ShowInfo()
{
Console.WriteLine("Doctor类的ShowInfo方法");
}
}
override 是针对父类中已经定义好的虚方法(virtual),可以重写
public class Person
{
public virtual void ShowInfo()
{
Console.WriteLine("Person类的虚方法");
}
}
override 是针对父类中已经定义好的虚方法(virtual),可以重写
// 称为派生类,也称为子类,继承Person
public class Doctor:Person
{
// override 是针对父类中已经定义好的虚方法(virtual),可以重写
public override void ShowInfo()
{
base.ShowInfo();
}
}