官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 涞水县| 定安县| 涪陵区| 汾西县| 玛多县| 伊川县| 崇文区| 类乌齐县| 阳新县| 普陀区| 临湘市| 泾川县| 大洼县| 陕西省| 峨眉山市| 武强县| 界首市| 东源县| 九寨沟县| 威宁| 会昌县| 唐河县| 云霄县| 伊春市| 大庆市| 台东县| 牙克石市| 陆川县| 陵水| 合江县| 兰州市| 四平市| 盖州市| 麻阳| 酒泉市| 阆中市| 循化| 西乌珠穆沁旗| 玛多县| 昌乐县| 临江市|