密封类用于限制用户继承该类。可以使用 密封的 关键词。关键字告诉编译器类是密封的,因此不能扩展。不能从密封类派生任何类。
null
以下是 语法 属于密封类:
sealed class class_name{ // data members // methods . . .}
方法也可以密封 ,在这种情况下,无法重写该方法。但是,方法可以被密封在继承它们的类中。如果你想将一个方法声明为sealed,那么它必须声明为sealed 事实上的 在它的底层。
下面的类定义定义了C#中的密封类:
在下面的代码中,创建一个密封类 密封级 并从程序中使用它。如果你运行这段代码,它就会正常工作。
C#
// C# code to define // a Sealed Class using System; // Sealed class sealed class SealedClass { // Calling Function public int Add( int a, int b) { return a + b; } } class Program { // Main Method static void Main( string [] args) { // Creating an object of Sealed Class SealedClass slc = new SealedClass(); // Performing Addition operation int total = slc.Add(6, 4); Console.WriteLine( "Total = " + total.ToString()); } } |
输出:
Total = 10
现在,如果它试图从一个密封的类继承一个类,那么就会产生一个错误,声明“它不能从 密封类 .
C#
// C# code to show restrictions // of a Sealed Class using System; class Bird { } // Creating a sealed class sealed class Test : Bird { } // Inheriting the Sealed Class class Example : Test { } // Driver Class class Program { // Main Method static void Main() { } } |
错误:
错误CS0509“示例”:无法从密封类型“测试”派生
考虑派生类中的密封方法的以下示例:
C#
// C# program to // define Sealed Class using System; class Printer { // Display Function for // Dimension printing public virtual void show() { Console.WriteLine( "display dimension : 6*6" ); } // Display Function public virtual void print() { Console.WriteLine( "printer printing...." ); } } // inheriting class class LaserJet : Printer { // Sealed Display Function // for Dimension printing sealed override public void show() { Console.WriteLine( "display dimension : 12*12" ); } // Function to override // Print() function override public void print() { Console.WriteLine( "Laserjet printer printing...." ); } } // Officejet class cannot override show // function as it is sealed in LaserJet class. class Officejet : LaserJet { // can not override show function or else // compiler error : 'Officejet.show()' : // cannot override inherited member // 'LaserJet.show()' because it is sealed. override public void print() { Console.WriteLine( "Officejet printer printing...." ); } } // Driver Class class Program { // Driver Code static void Main( string [] args) { Printer p = new Printer(); p.show(); p.print(); Printer ls = new LaserJet(); ls.show(); ls.print(); Printer of = new Officejet(); of.show(); of.print(); } } |
输出:
display dimension : 6*6Printer printing....display dimension : 12*12LaserJet printer printing....display dimension : 12*12Officejet printer printing....
说明: 在上面的C#代码中,Printer类具有尺寸为6*6的显示单元,LaserJet类通过将其重写为尺寸为12*12实现了show方法。如果任何类将继承LaserJet类,那么它将具有相同的12*12维度,并且不能实现自己的维度,即它不能具有15*15、16*16或任何其他维度。因此,LaserJet调用将密封show方法,以防止进一步重写它。
为什么要封闭课堂?
- 密封类用于阻止要继承的类。不能从中派生或扩展任何类。
- 实现密封的方法是为了使其他类不能推翻它并实现自己的方法。
- 密封类的主要目的是从用户那里提取继承属性,这样用户就无法从密封类中获取类。当您有一个包含静态成员的类时,最好使用密封类。 例如 系统的“笔”和“刷”类。绘图名称空间。Pens类表示标准颜色的笔。这个类只有静态成员。例如,“Pens.Red”代表红色的笔。类似地,“笔刷”类表示标准笔刷。“画笔.红色”代表红色的画笔。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END