Challenge: Modifiers Practice
メニューを表示するにはスワイプしてください
You are given a class named Person with a field to store the name. Additionally, there are two classes named Student and Teacher which derive from Person.
There are some errors in the program because of some incomplete code. Your task is to complete the code by:
- Making both
StudentandTeacherinherit from thePersonclass; - Ensure that the
namefield is accessible in the child classes but inaccessible from anywhere else.
index.cs
12345678910111213141516171819202122232425262728293031323334353637383940414243444546using System; public class Person { // Field to store the name string name; } public class Student { public Student(string name) { this.name = name; } public void Study() { Console.WriteLine($"{name} is studying."); } } public class Teacher { public Teacher(string name) { this.name = name; } public void Teach() { Console.WriteLine($"{name} is teaching."); } } public class Program { public static void Main(string[] args) { Teacher t = new Teacher("Hannah"); Student s = new Student("Mark"); t.Teach(); s.Study(); } }
- In this task first you need to use the concept of derived classes, then the access modifiers.
- We use the
:symbol to specify the parent class in the definition of a child (derived) class. - Recall which access modifier is appropriate for the
namefield to hide it from the outside of the class but make it accessible from the child classes.
index.cs
123456789101112131415161718192021222324252627282930313233343536373839404142434445using System; public class Person { // Field to store the name protected string name; } public class Student : Person { public Student(string name) { this.name = name; } public void Study() { Console.WriteLine($"{name} is studying."); } } public class Teacher : Person { public Teacher(string name) { this.name = name; } public void Teach() { Console.WriteLine($"{name} is teaching."); } } public class Program { public static void Main(string[] args) { Teacher t = new Teacher("Hannah"); Student s = new Student("Mark"); t.Teach(); s.Study(); } }
すべて明確でしたか?
フィードバックありがとうございます!
セクション 4. 章 4
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 4. 章 4