- Hands-On Object:Oriented Programming with C#
- Raihan Taher
- 257字
- 2021-07-02 12:44:43
The sealed class
One of the principles of OOP is inheritance, but sometimes you may need to restrict inheritance in your code for the sake of your application's architecture. C# provides a keyword called sealed. If this keyword is placed before a class's signature, the class is considered a sealed class. If a class is sealed, that particular class can't be inherited by other classes. If any class tries to inherit a sealed class, the compiler will throw an error. Structs can also be sealed, and in that case, no class can inherit that struct.
Let's look at an example of a sealed class:
sealed class Animal {
public string name;
public int ageInMonths;
public void Move(){
Console.WriteLine("Moving");
}
public void Eat(){
Console.WriteLine("Eating");
}
}
public static void Main(){
Animal dog = new Animal();
dog.name = "Doggy";
dog.ageInMonths = 1;
dog.Move();
dog.Eat();
}
In the preceding example, we can see how we can create a sealed class. Just using the sealed keyword before the class keyword makes the class a sealed class. In the preceding example, we created an Animal sealed class, and in the main method, we instantiated the class and used it. This is now working fine. However, if we try to create a Dog class that will inherit the Animal class, as in the following code, then the compiler will throw an error, saying that the sealed Animal class can't be inherited:
class Dog : Animal {
public char gender;
}
Here is a screenshot of what the compiler will show:

- Java范例大全
- PHP 編程從入門到實踐
- 學習OpenCV 4:基于Python的算法實戰
- Learning PHP 7
- Swift 4 Protocol-Oriented Programming(Third Edition)
- UNIX Linux程序設計教程
- 基于SpringBoot實現:Java分布式中間件開發入門與實戰
- Mastering AWS Security
- PHP 7從零基礎到項目實戰
- 從0到1:HTML5 Canvas動畫開發
- Getting Started with Web Components
- Building Web Applications with Flask
- Mastering VMware Horizon 6
- ReactJS Blueprints
- Python程序設計教程