Abstract Classes in microsoft dot net

Each type of Window has a different shape and appearance. Drop-down listboxes look very different from buttons. Clearly, every subclass of Window should implement its own DrawWindow() method — but so far, nothing in the Window class enforces that they must do so. To require subclasses to implement a method of their base, you need to designate that method as abstract.

An abstract method has no implementation. It creates a method name and signature that must be implemented in all derived classes. Furthermore, making at least one method of any class abstract has the side effect of making the class abstract.

Abstract classes establish a base for derived classes, but it is not legal to instantiate an object of an abstract class. Once you declare a method to be abstract, you prohibit the creation of any instances of that class.

Abstract classes should not just be an implementation trick; they should represent the idea of an abstraction that establishes a "contract" for all derived classes. In other words, abstract classes mandate the public methods of the classes that will implement the abstraction.

The idea of an abstract Window class ought to lay out the common characteristics and behaviors of all windows, even though you never intend to instantiate the abstraction Window itself.

The idea of an abstract class is implied in the word "abstract." It serves to implement the abstraction "Window" that will be manifest in the various concrete instances of Window, such as browser window, frame, button, listbox, drop-down, and so forth. The abstract class establishes what a Window is, even though we never intend to create a "Window" per se.

Thus, if you were to designate DrawWindow() as an abstract method in the Window class, the Window class would become abstract. Then you could derive from Window, but you could not create any Window instances. If the Window class is an abstraction, there is no such thing as a simple Window object, only objects derived from Window.

Making Window.DrawWindow() abstract means that each class derived from Window would have to implement its own DrawWindow() method. If the derived class failed to implement the abstract method, that derived class would also be abstract, and again no instances would be possible.

Designating a method as abstract is accomplished by placing the abstract keyword at the beginning of the method definition, as follows:

abstract public void DrawWindow();

(Because the method can have no implementation, there are no braces, only a semicolon.)

If one or more methods are abstract, the class definition must also be marked abstract, as in the following:

abstract public class Window

No comments:

Post a Comment