根据上面的写一个继承
时间: 2024-02-28 11:53:13 浏览: 78
继承的小例子
4星 · 用户满意度95%
以下是一个简单的C#继承示例代码:
```csharp
using System;
namespace InheritanceExample
{
class Person
{
private string name;
private int age;
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
public string GetName()
{
return name;
}
public void SetName(string name)
{
this.name = name;
}
public int GetAge()
{
return age;
}
public void SetAge(int age)
{
this.age = age;
}
public virtual void SayHello()
{
Console.WriteLine("Hello, my name is {0}, I'm {1} years old.", name, age);
}
}
class Student : Person
{
private string school;
public Student(string name, int age, string school) : base(name, age)
{
this.school = school;
}
public string GetSchool()
{
return school;
}
public void SetSchool(string school)
{
this.school = school;
}
public override void SayHello()
{
Console.WriteLine("Hello, my name is {0}, I'm {1} years old, and I study at {2}.", GetName(), GetAge(), school);
}
}
class Program
{
static void Main(string[] args)
{
Person person = new Person("Tom", 18);
person.SayHello();
Student student = new Student("Jerry", 20, "MIT");
student.SayHello();
}
}
}
```
以上代码实现了一个Student类,继承自Person类,其中:
- 第14-30行:定义了Person类,包括name和age两个私有字段和访问器方法,以及SayHello方法;
- 第32-50行:定义了Student类,继承自Person类,新增了school字段和访问器方法,以及重写了SayHello方法;
- 第53-62行:在Main函数中创建Person对象和Student对象,分别调用SayHello方法。
可以看到,继承可以有效地实现代码的重用,并且在子类中可以扩展父类的功能,同时也能保证代码的可维护性和安全性。
阅读全文