- Derived Class : is child class that inherits from another class.
- Base Class : is the parent class which the class being inherited from.
We use the : symbol to inherit from a class.
class Person { // base class
public string type = "Person";
public void say() {
Console.WriteLine("Hello");
}
}
class Student : Person { // derived class
public string type = "Student";
public int studentId = 1;
}
class Program {
static void Main(string[] args) {
Student student = new Student();
student.say();
Console.WriteLine(student.type +
" " + student.studentId);
}
}
Result :
Hello
Student 1
sealed Keyword
If you don’t want others class inherit from a class, you can use sealed keywordsealed class Person {You would get error message that 'Student' : cannot derive from sealed type.
public string type = "Person";
public void say() {
Console.WriteLine("Hello");
}
}
class Student : Person {
...
}
No comments :
Post a Comment