C#
  Home arrow C# arrow Page 3 - Polymorphism in C#
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Polymorphism in C#
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 26
    2007-05-17

    Table of Contents:
  • Polymorphism in C#
  • Versioning with new and override
  • Abstract Classes
  • The Root of All Classes: Object
  • Boxing and Unboxing Types
  • Summary

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Polymorphism in C# - Abstract Classes


    (Page 3 of 6 )

    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 ownDrawWindow()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.

    Thus, if you were to designateDrawWindow()as an abstract method in theWindowclass, theWindow class itself would become abstract. Then you could derive fromWindow, but you could not create anyWindowinstances. If theWindowclass is an abstraction, there is no such thing as a simpleWindowobject, only objects derived fromWindow.

    MakingWindow.DrawWindow()abstract means that each class derived fromWindow would have to implement its ownDrawWindow()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.


    The Idea Behind Abstraction

    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. An alternative to usingabstractis to define an interface, as described in Chapter 13.


    Designating a method as abstract is accomplished by placing theabstractkeyword at the beginning of the method definition:

      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 markedabstract, as in the following:

      abstract public class Window

    Example 11-3 illustrates the creation of an abstract Window class and an abstractDrawWindow()method.

    Example 11-3. Abstract methods

    using System;

    public abstract class Window
    {
      
    // constructor takes two integers to
      
    // fix location on the console
      
    public Window( int top, int left )
      
    {
         
    this.top = top;
          this.left = left;
       }

       // simulates drawing the window
       // notice: no implementation
       public abstract void DrawWindow();

       protected int top;
       protected int left;
    }     // end class Window

    // ListBox derives from Window
    public class ListBox : Window
    {
      
    // constructor adds a parameter
       public ListBox(
       int top,
       int left,
       string contents ) : base( top, left ) // call base constructor
       {

          listBoxContents = contents;
       }

       // an overridden version implementing the
       // abstract method
       public override void DrawWindow()
       {
         
    Console.WriteLine( "Writing string to the listbox: {0}",
         
    listBoxContents );
       }
       private string listBoxContents; // new member variable
    }     // end class ListBox

    public class Button : Window
    {
       public Button(
       int top,
       int left ) : base( top, left ) { }

       // implement the abstract method
       public override void DrawWindow()
       {
         
    Console.WriteLine( "Drawing a button at {0}, {1}\n",
          top, left );
       }
    }       // end class Button

    public class Tester
    {
       static void Main()
       {
         
    Window[] winArray = new Window[3];
          winArray[0] = new ListBox( 1, 2, "First List Box" );
          winArray[1] = new ListBox( 3, 4, "Second List Box" );
          winArray[2] = new Button( 5, 6 );

          for ( int i = 0; i < 3; i++ )
          {
            
    winArray[i].DrawWindow();
          }     // end for loop
       }       // end main
    }          // end class Tester

    The output looks like this:

      Writing string to the listbox: First List Box
      Writing string to the listbox: Second List Box
      Drawing a button at 5, 6

    In Example 11-3, theWindowclass has been declared abstract and therefore cannot be instantiated. If you replace the first array member:

      winArray[0] = new ListBox(1,2,"First List Box");

    with this code:

      winArray[0] = new Window(1,2);

    the program generates the following error at compile time:

    Cannot create an instance of the abstract class or interface 'Window'

    You can instantiate theListBoxandButtonobjects because these classes override the abstract method, thus making the classes concrete (that is, not abstract).

    Often an abstract class will include non-abstract methods. Typically, these will be marked virtual, providing the programmer who derives from your abstract class the choice of using the implementation provided in the abstract class, or overriding it. Once again, however, all abstract methods must, eventually, be overridden in order to make an instance of the (derived) class.

    Sealed Classes

    The opposite side of the design coin from abstract is sealed. In contrast to an abstract class, which is intended to be derived from and to provide a template for its subclasses to follow, a sealed class does not allow classes to derive from it at all. The sealed keyword placed before the class declaration precludes derivation. Classes are most often marked sealed to prevent accidental inheritance.

    If you changed the declaration ofWindowin Example 11-3 fromabstracttosealed(eliminating theabstractkeyword from theDrawWindow()declaration as well), the program fails to compile. If you try to build this project, the compiler returns the following error message:

      'ListBox' cannot inherit from sealed type 'Window'

    among many other complaints (such as that you cannot create a new protected member in a sealed class).

    Microsoft recommends using sealed when you know that you won’t need to create derived classes, and also when your class consists of nothing but static methods and properties.

    More C# Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "Learning C# 2005, Second Edition,"...
     

    Buy this book now. This article is excerpted from chapter 11 of Learning C# 2005, Second Edition, written by Jesse Liberty and Brian MacDonald (O'Reilly, 2006; ISBN: 0596102097). Check it out today at your favorite bookstore. Buy this book now.

    C# ARTICLES

    - C# and XML
    - Pointers and Arrays in C#
    - C# 3.0 Extension Methods
    - Overloading Operators in C#
    - Iterators and Nullable Types
    - Patterns and Iterators in C#
    - C# Exceptions
    - Methods in C#
    - Delegates and Events in C#
    - Advanced C#
    - Working with Regular Expressions in C#
    - Sending Simple E-Mail in C#
    - Building C# Comparable Objects: IComparable ...
    - Color Transformation Applications in C# GDI+...
    - Performing Color Transformation Operations i...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway
    Stay green...Green IT