7.13. Sealed methods (Java final methods)

It will be wise to make sure you understand section 7.10 before reading this section.

C# sealed methods are simply Java final methods – methods which cannot be overridden in subclasses. Here is an example of how an attempt to override a sealed method will result in a compilation error:

 1: using System;
 2:
 3: class GrandChild:Child{
 4:   public static void Main(){
 5:   }
 6:
 7:   // this will cause a compilation error.
 8:   public override void DoSomething(){
 9:     Console.WriteLine("running version 3");
10:   }
11: }
12:
13: class Child:Parent{
14:   public override sealed void DoSomething(){
15:     Console.WriteLine("running version 2");
16:  }
17: }
18:
19: class Parent{
20:   public virtual void DoSomething(){
21:     Console.WriteLine("running version 1");
22:   }
23: }

Compilation error:

test.cs(8,24): error CS0239: 'GrandChild.DoSomething()' :
cannot override inherited member 'Child.DoSomething()'
because it is sealed

Like Java

Sealed methods cannot be overridden in subclasses.

Additional note

It doesn't make sense to declare a method as sealed unless it is itself an overridden method of a subclass. If you are defining a new method in a class, and do not want subclasses to override it, simply do not declare the method using the virtual modifier. Non-virtual methods cannot be overridden in subclasses, though they can be hidden (see section 7.11). In other words, you almost always use the sealed modifier together with the override modifier in a method declaration.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.164.141