Monday, March 23, 2020

[C#] Derived and Base Class, sealed keyword

In C#, you can  inherit fields and methods from another class. It’s inheritance..

  1. Derived Class : is child class that inherits from another class.
  2. 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 keyword
sealed class Person {
  public string type = "Person";
  public void say() {
    Console.WriteLine("Hello");
  }
}

class Student : Person {
  ...
}
You would get error message that 'Student' : cannot derive from sealed type.

No comments :

Post a Comment