Saturday, July 26, 2008

Sealed Classes

Classes can be declared as sealed. This is accomplished by putting the sealed keyword before the keyword class in the class definition. For example:

public sealed class classSealed
{
// Class members here.
public string ID;
public double Price;

}
In the following code listing the implementation of a sealed class has been tested.

classSealed sc=new classSealed();
sc.ID=”C1”;
sc.Price=500.00;
double Samt=sc. CalculatePrice();
Response.Write(“Total Net Price of Product : “ +” “+sc.ID +” “+is+” “+Samt);
Response.Write(“
”);


A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes are primarily used to prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster. Sealing a class means one can not derive from it. Sealing a method means one can not override it. In C# structs are implicitly sealed; therefore, they cannot be inherited. If we try to inherit from a sealed class in another class we will get compile time error about Inconsistent accessibility (code is shown in following code listing).

public class TestClass : classSealed
{
}

In C# a method can not be declared as sealed. However when we override a method in a derived class, we can declare the overridden method as sealed as shown below. By declaring it as sealed, we can avoid further overriding of this method.

public class testClass
{
public int x;
public int y;
public virtual void testMethod(){

}

}

public class TestClass: testClass
{
public override sealed void testMethod()
{

}
}

1 comment:

caceyideker said...

NJ Casino 2021 | Play Real Money Online - JtmHub
› games › casino 강원도 출장안마 › games › casino Play online for real money and win real money in 파주 출장마사지 NJ. 속초 출장샵 Claim 경상북도 출장마사지 your 대구광역 출장샵 bonus code and claim your bonus!