sealed

honggarae 10/04/2023 432

Example

In the example below, class B is inherited from class a, but any classes cannot inherit from class B.

Class A {}

Sealed Class B: A {}

can also be able to rewrite the virtual method or virtual property method or attribute in the base class Use Sealed modifiers. This will allow you to allow classes to inherit from your class and prevent them from overwriting specific false methods or virtual properties.

In the following example, C inherit from B, but C cannot rewrite declarations in A and the virtual function F seal in B.

Class a

{

protected virtual void f ()

{

console.writeline (" AF ");

}

protected virtual void f2 ()

{

console.writeline (" a.f2 ") ;

}

Class B: a

{

Sealed Protected Override Void f ()

{

console.writeline ("bf");

}

protected override void f2 ()

< P> {

console.writeline ("B.F2");

sealed

}

}

Class C: B

{

protected override void f2 ()

{

console.writeline ("c.f2");

< P>}

}

When a new method or attribute is defined in the class, the derived class will be rewritten by rewriting these methods or by declaring these methods or attributes as Virtual. Attributes (default is hidden approaching method, don't rewrite). The Abstract modifier is used to seal is a wrong approach because the abstract class must be inherited by a class that provides an abstract method or attribute. Sealed modifiers must always be used with Override when applied to methods or properties. Since the structure is implicitly sealed, they cannot be inherited.

Sealed Class SealedClass

{

public int x;

public int y;

}

Class SealedTest2

{

static void main ()

{

SealedClass sc = New SealedClass ();

sc.x = 110;

sc.y = 150;

console.writeLine ("x = {0}, y = {1}" , sc.x, sc.y);

}

}

// output: x = 110, y = 150

In the previous example, you may try to use the following statement inheritance: class myderivedc: SealedClass {} // error will generate an error message:

'myderivedc' Cannot Inherit from Sealed Class' SealedClass'.

Latest: Beijing National Hotel

Next: Essential Items to Bring for Your Long-Time Camping Adventure