NenTang
Học tập · thực hành · tiến bộ mỗi ngày
45 / 69

Lập trình căn bản C# Chương 5 Bài 11

Chương 5 Bài 11. Làm quen Hướng đối tượng trong C#

legacy-admin-baitap-1

2 thg 2, 2025

1.726 lượt xem

32 phút

Mô tả bài toán

  • Create a new project, and include in it the class Person that you just created.
  • Create a class "Student" and another class "Teacher", both descendants of "Person".
  • The class "Student" will have a public method "GoToClasses", which will write on screen "I’m going to class."
  • The class "Teacher" will have a public method "Explain", which will show on screen "Explanation begins". Also, it will have a private attribute "subject", a string.
  • The class Person must have a method "SetAge (int n)" which will indicate the value of their age (eg, 20 years old).
  • The student will have a public method "ShowAge" which will write on the screen "My age is: 20 years old" (or the corresponding number).
  • You must create another test class called "StudentAndTeacherTest" that will contain "Main" and:
    • Create a Person and make it say hello
    • Create a student, set his age to 21, tell him to Greet and display his age
    • Create a teacher, 30 years old, ask him to say hello and then explain.

Cách giải quyết

Tạo các class sau:
  • Class Person, có:
    • Thuộc tính (property):
      • Age: tuổi
    • Phương thức (method):
      • Greet: hiển thị câu chào mừng "Hello"
      • SetAge: gán giá trị cho thuộc tính tuổi Age
  • Class Student kế thừa từ class Person, có thêm:
    • Phương thức (method):
      • ShowAge: hiển thị thông tin tuổi.
  • Class Teacher kế thừa từ class Person, có thêm:
    • Thuộc tính (property):
      • subject: môn giảng dạy
    • Phương thức (method):
      • Explain: giảng bài cho Sinh viên

Source code

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5 
6namespace TeacherAndStudentOOP
7{
8 class Person
9 {
10 protected int age;
11 
12 public void Greet()
13 {
14 Console.WriteLine("Hello");
15 }
16 
17 public void SetAge(int n)
18 {
19 age = n;
20 }
21 }
22 
23 class Student : Person
24 {
25 public void ShowAge()
26 {
27 Console.WriteLine("My age is: {0} years old", age);
28 }
29 }
30 
31 class Teacher : Person
32 {
33 private string subject;
34 
35 public void Explain()
36 {
37 Console.WriteLine("Explanation begins");
38 }
39 }
40 
41 class StudentAndTeacherTest
42 {
43 static void Main()
44 {
45 bool debug = false;
46 
47 Person myPerson = new Person();
48 myPerson.Greet();
49 
50 Student myStudent = new Student();
51 myStudent.SetAge(21);
52 myStudent.Greet();
53 myStudent.ShowAge();
54 
55 Teacher myTeacher = new Teacher();
56 myTeacher.SetAge(30);
57 myTeacher.Greet();
58 myTeacher.Explain();
59 
60 if (debug)
61 Console.ReadLine();
62 Console.ReadKey();
63 }
64 }
65}

Github

https://github.com/kellyfire611/learning.nentang.vn-csharp/blob/master/src/TeacherAndStudentOOP/Program.cs