Microsoft Visual C#.NET 2003 Kick Start
Say that you decided to sell the Window class commercially. In that case, note that there's no guarantee that programmers would implement their own Open methods ; they might leave the default Open method in place. If you consider that inappropriateif you want to force those programmers to implement their own Open method if they derive classes from your Window classyou can declare the Open method abstract . You declare a method abstract simply by using the abstract keyword, as you see in ch04_05.cs, Listing 4.5. Don't give the method any body; just end the declaration of the method with a semicolon, as you see in Listing 4.5. When you give a class an abstract method, that method must be overridden in any derived classes, and in addition, the class must be declared with the abstract keyword (even if it includes non-abstract methods in addition to the abstract methods), as you can also see in ch04_05.cs.
Listing 4.5 Overriding Abstract Methods (ch04_05.cs)
public class ch04_05 { public static void Main() { Menu menu = new Menu(); menu.Open(); } } abstract public class Window { abstract public void Open(); } public class Menu : Window { private string openingMessage = "Displaying items..."; public override void Open() { System.Console.WriteLine(openingMessage); } } Here are the results of ch04_05.cs:
C:\>ch04_05 Displaying items...
Sealed Classes
Abstract classes are designed to be inheritedbut there's an opposite option available too. C# has sealed classes, which are designed not to be inherited. If you mark a class as sealed with the sealed keyword, that class cannot be inherited:
sealed public class Window { private string openingMessage = "Opening..."; public void Open() { System.Console.WriteLine(openingMessage); } } If you try to derive the Menu class from this version of Window , you'll see a message like this:
ch04_01.cs(23,14): error CS0509: 'Menu' : cannot inherit from sealed class 'Window'
|