返回顶部

一缕半夏微光

温柔半两,从容一生

导航

设计编写一个控制台应用程序,练习类的继承(C#)

一、效果如下:

二、代码如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Net_2_1
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             //Student
14             Student student = new Student();
15             Console.WriteLine("请输入学生的姓名:");
16             student.name = Console.ReadLine();
17             Console.WriteLine("请输入学生的姓名-属性:");
18             student.Name = Console.ReadLine();
19             Console.WriteLine("请输入学生的年龄:");
20             student.age = int.Parse(Console.ReadLine());
21             Console.WriteLine("请输入学生的学校:");
22             student.school = Console.ReadLine();
23             Console.WriteLine("Student-姓名:{0}", student.name);
24             Console.WriteLine("Student-姓名-属性:{0}", student.Name);
25             Console.WriteLine("Student-年龄:{0}", student.age);
26             Console.WriteLine("Student-学校:{0}", student.school);
27             student.Work();
28             //Employer
29             Employer employer = new Employer();
30             Console.WriteLine("请输入员工的姓名:");
31             employer.name = Console.ReadLine();
32             Console.WriteLine("请输入员工的年龄:");
33             employer.age = int.Parse(Console.ReadLine());
34             Console.WriteLine("请输入员工的工作单位:");
35             employer.workplace = Console.ReadLine();
36             Console.WriteLine("Employer-姓名:{0}", employer.name);
37             Console.WriteLine("Employer-年龄:{0}", employer.age);
38             Console.WriteLine("Employer-工作单位:{0}", employer.workplace);
39             employer.Work();
40 
41             Console.ReadKey();
42         }
43     }
44 
45     //抽象类 People,具有”姓名”,”年龄”字段,”姓名”属性,Work 方法
46 
47     abstract class People
48     {
49         public String name; //姓名
50         public String Name
51         { //姓名属性
52             get; 
53             set; 
54         }
55         public int age;//年龄
56         public abstract void Work();//work方法 
57     }
58 
59     //由抽象类 People 派生出学生类 Student 和职工类 Employer,继承 People 类,并覆盖Work 方法
60 
61     class Student : People  //学生类,继承people类
62     {
63         public String school; //派生类 Student 增加”学校”字段
64         public override void Work()
65         {
66             Console.WriteLine("学生类Student");
67         }
68     }
69     class Employer : People //Employer类,继承people类
70     {
71         public String workplace;//派生类 Employer 增加”工作单位”字段
72         public override void Work()
73         {
74             Console.WriteLine("职工类Employer");
75         }
76 
77     }
78 }

参考链接:https://www.cnblogs.com/miria-486/p/10072879.html

posted on 2021-11-17 21:11  一缕半夏微光  阅读(142)  评论(0编辑  收藏  举报