SunQuest
 
       ASP.NET
  Home arrow ASP.NET arrow Chapter 8 Shadow Fields Override Virtual M...
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 
Dedicated Servers 
Actuate Whitepapers 
VeriSign Whitepapers 
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? 
ASP.NET

Chapter 8 Shadow Fields Override Virtual Methods
By: aspfree
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 5
    2002-11-16

    Table of Contents:

    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

    Free Web 2.0 Code Generator! Generate data entry and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

    A Twisted Look at Object Oriented Programming in C#

    By Jeff Louie
    11/13/2002

    I must admit that my first exposure to object oriented programming (OOP) wasfrustrating and difficult. As a hobbyist I have struggled through Z80 assemblyand EPROM burners, BASIC, Turbo Pascal, Java, C++ COM and now C#. The move toevent driven programming and then to object oriented programming presented majorconceptual hurdles to my function driven sequential programming mindset. The “aha”moment when OOP made sense was most gratifying, but did not come quickly oreasily. It has been a few years since I “got” the OOP mindset and I feelcomfortable enough now to try to help fellow travelers with this journey. If OOPcomes easily to you, feel free to skip this tutorial. If you are having problemsgetting your mind around objects and inheritance I hope this tutorial can helpyou. This tutorial does not represent a conventional teaching method. It assumesa passing knowledge of the C# language and familiarity with the Visual Studio.NET IDE. This is a work in progress and may require correction orrevisions.

    Comments are actively requested (email: Jeff_Louie@yahoo.com).

    Useful Texts

    I highly recommend the following books. Much of my understanding of OOP hasbeen gleamed from these “classic” texts and then reinforced from codingdatabase projects in Java, C++ and C#. At all times I willfully try to avoidplagiarizing these authors, but my understanding of OOP is so closely tied tothese texts that I must cite them as sources of knowledge right from thestart!

    Object-Oriented Analysis and Design with Applications GradyBooch, Second Edition, Addison-Wesley, 1994, 589pp.

    Design Patterns Elements of Reusable Object-Oriented SoftwareGamma Helm, Johnson and Vlissides, Addison-Wesley, 1994, 395pp.

    Object-Oriented Software Construction Second Edition BertrandMeyer, Prentice Hall, 1997, 1254pp.

    Of course, some of this material is a descendent of my writing from our nowout of print book:

    Visual Café for Java Explorer Database Development EditionBrogden Louie and Tittle, Coriolis, 1998, 595pp.

    Chapter 8 "Shadow Fields, Override VirtualMethods"

    Well, I am going to finish this "nuts and bolts" chapter before I flame out! I promised thatI would discuss overriding, so I am going to make good on this promise. Ingeneral when you extend a class, you shadow fields with the same name in thebase class and override virtual methods with the same name and parameter list inthe base class. Overriding makes the base class method invisible. Shadowinga field, only hides the field from view. You can still explicitly touch thehidden shadowed field if you wish. You cannot touch an invisible overriddenmethod. To demonstrate the difference between shadowing and overriding I resort,as usual, to twisted code!

    First, you can create a sample base class with a public read only field"toastTime" and a virtual method "MakeToast()":

    class Base 
    
    {
    public readonly int toastTime= 60;
    public virtual void MakeToast()
    {
    System.Console.WriteLine("MakeToastInSeconds: "
    + toastTime.ToString());
    }
    }

    Declaring the only method virtual explicitly allows a designer to overridethe MakeToast() method in a subclass. (Contrast this tothe approach in Java in which all methods are virtual by default.) This is important, since you areexplicitly allowing a subclass to completely rewrite the implementation of theMakeToast() method and in doing so make it totally invisible!

    Shadow Fields, Override Methods in the Base Class

    Now you can extend or subclass the class Base:

    /// <summary>
    
    /// Summary description for SubClass
    /// </summary>
    class SubClass : Base
    {
    public readonly
    new int toastTime= 1;
    public
    override void MakeToast()
    {
    System.Console.WriteLine("MakeToastInMinutes: "
    + toastTime.ToString());
    }
    }

    Note: You must explicitly tell the compiler that you are overriding thevirtual base class method MakeToast() with the key word overrideand that you are hiding the base field with the key word new.(You cannot override a field in a base class.)

    Overriding the method MakeToast makes the baseclass method with the same name and signature invisible to the caller of the class. This isin contrast to the base class field toastTime. The base class field toastTime is shadowed,but still potentially visible to the caller. You have shadowed a base class field and overridden a base class method.

    You can demonstrate the behavior of shadowed fields with the following test code:

    SubClass sc= new SubClass();
    
    System.Console.WriteLine(sc.toastTime.ToString()); // --> 1
    Base super= (Base)sc;
    System.Console.WriteLine(super.toastTime.ToString()); // --> 60

    In the above code snippet, the type of the reference variable determineswhich value of toastTime can be touched with the reference variable. Touchingthe field with a reference of type SubClass tells the compiler that you want totouch the the toastTime field of class SubClass. Casting thereference variable to the base type, tells the compiler that you want to touchthe toastTime field of the type Base. Both fields are potentially visible to thecaller. The base class field is shadowed, but still touchable.

    You can demonstrate the behavior of an overridden method with the followingtest code. This code demonstrates that the overridden base class method MakeToast isinvisible. You cannot touch the overridden method even if you cast the referenceto the base type.

    SubClass sc= new SubClass();
    
    sc.MakeToast(); // --> MakeToastInMinutes: 1
    Base super= (Base)sc;
    super.MakeToast(); // --> MakeToastInMinutes: 1

    Despite the cast, only the derived(specialized) classmethod is visible. If you think about it, this behavior is absolutely essential to polymorphism. Overriding insures that the"proper" implementation of a polymorphic method is called at runtime.You can demonstrate the proper polymorphic behavior with a little sample code. Here is yetanother version of the Drawable class, now with a default implementation ofDrawYourself.

    class Drawable 
    
    {
    public virtual void DrawYourself()
    {
    System.Console.WriteLine("Drawable");
    }
    }
    class Square : Drawable
    {
    public override void DrawYourself()
    {
    System.Console.WriteLine("Square");
    }
    }
    class Circle : Drawable
    {
    public override void DrawYourself()
    {
    System.Console.WriteLine("Circle");
    }
    }

    Here is the sample code that demonstrates that the "proper" implementationis called at runtime.

    Drawable draw= new Drawable();
    
    draw.DrawYourself(); //--> Drawable
    draw= new Square();
    draw.DrawYourself(); //--> Square
    draw= new Circle();
    draw.DrawYourself(); //--> Circle

    Overriding insures that the proper superclass implementation is always called at runtime. The magic of polymorphism issecure.

    You Can Hide a Method

    For completeness sake, I will mention that you can hide a virtualmethod using the key word new instead of the keyword override. Go ahead. Edit the previous codesample and replace the key word override with the key word new.

    This is the new behavior that breaks polymorphism:
    Drawable draw= new Drawable();
    
    draw.DrawYourself(); //--> Drawable
    draw= new Square();
    draw.DrawYourself(); //--> Drawable
    draw= new Circle();
    draw.DrawYourself(); //--> Drawable

    Perhaps not what you wanted!

    All Rights Reserved Jeff Louie 2002


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More ASP.NET Articles
    More By aspfree

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! Driving Business Success with Rational Process Library

    Join this webcast, to learn how the Rational Process Library can help with compliance issues, drive process improvement, and assist in service-oriented architecture (SOA) or Agile development. We will take a peek into the Rational Process Library with content around software and systems engineering (including RUP), operations and systems management, program and portfolio management, and asset and SOA governance.
    FREE! Go There Now!


    NEW! IBM Enterprise Modernization Sandbox for System z: Architecture

    Analysts, architects, and developers who have existing COBOL or PL/I skills and want to extend those skills to deploy new workloads on the mainframe can use the IBM Enterprise Modernization Sandbox for System z to find hands-on walkthroughs of common real world scenarios. The scenarios provide examples of how to rapidly design, create, assemble, test, and deploy high-quality Web, Web services, portal, and SOA applications for IBM CICS, IBM IMS, and IBM WebSphere Application Server.
    FREE! Go There Now!


    NEW! Integrating XML into Your Enterprise Using Data Federation

    XML has become a common way of storing business data as flat files and many data server vendors including IBM have provided ways to store this data within relational database systems. Increasingly collections of XML files are accessed like databases using an xQuery and other XML standard mechanisms. Businesses find the need to combine the traditional tabular structured data with XML formatted data. In this webcast, you’ll learn about IBM’s WebSphere Federation Server technology, which provides users with the ability to integrate these two data formats.
    FREE! Go There Now!


    NEW! Rational Talks to You: Grady Booch on Architecture

    Join this Rational Talks to You teleconference on November 29 at 1:00 pm ET to participate in an interactive discusssion with Grady Booch around architecture and reuse. Get your questions answered!
    FREE! Go There Now!


    NEW! Try the IBM SOA Sandbox for Process

    Visit IBM developerWorks to try the IBM SOA Sandbox for process. The SOA Sandbox for process focuses on providing a trial environment with the necessary tooling and components required to gain a better understanding of business processes and how to best improve existing business processes to derive value quickly.
    FREE! Go There Now!


    NEW! Understanding Web application security challenges

    As businesses grow increasingly dependent upon Web applications, these complex entities grow more difficult to secure. Most companies equip their Web sites with firewalls, Secure Sockets Layer (SSL), and network and host security, but the majority of attacks are on applications themselves – and these technologies cannot prevent them. This paper explains what you can do to help protect your organization, and it discusses an approach for improving your organization’s Web application security.
    FREE! Go There Now!


    NEW! Webcast: Accelerating Software Innovation with System z

    Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, where he will overview Rational’s new offerings and programs to help customers accelerate software innovation on System z. He will discuss how these solutions help organizations extend their core business processes toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time.
    FREE! Go There Now!


    NEW! Webcast: Application security testing and Web compliance

    Join the IBM Watchfire team for an informative discussion on techniques and best practices to proactively manage Web application security and how to effectively build application security testing into the software development lifecycle (SDLC). In this Software Delivery Platform webcast you will learn: How to better understand potential web application security vulnerabilities, best practices and how to effectively integrate application security testing into the software development lifecycle, the importance of detecting and removing software vulnerabilities during application development.
    FREE! Go There Now!


    NEW! Webcast: Quickly provide customized, integrated user interfaces with Lotus Notes 8

    IBM Lotus Notes 8 provides a wide range of developers the ability to provide customized, integrated user interfaces via composite applications and via custom sidebar and toolbar plug-ins. This webcast provides you with tips and techniques to use with out-of-the-box capabilities of Lotus Notes 8, and survey how you can share useful components within your own company and within a larger community.
    FREE! Go There Now!


    NEW! Webcast: Striking the right balance between manual and automated testing

    Join this webcast to learn how IBM Rational's Functional Testing solution enables you to implement automation your way, at your pace, with your existing staff. In this webcast, you’ll learn how you can eliminate redundancy of manual test scripts, reduce errors, and increase test coverage through test automation. After this presentation you will understand how IBM Rational Functional Testing solution can streamline your manual testing and make test automation easily attainable.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    ASP.NET ARTICLES

    - Enhancing PHP Via the ASP.NET AJAX Framework...
    - Enhancing PHP Programming with the ASP.NET A...
    - Classes and ASP.NET AJAX
    - Using ASP.NET AJAX
    - Building a Simple Storefront with LINQ
    - Developing a Dice Game Using ASP.NET Futures...
    - Completing an ASP.NET AJAX Server-Centric Ba...
    - Information Management for an ASP.NET AJAX S...
    - Comment and Order Management for an ASP.NET ...
    - Back-end Management Tasks for an ASP.NET AJA...
    - User Information Management for an ASP.NET A...
    - Adding Comments and Search to an ASP.NET AJA...
    - Order-Related Modules for an ASP.NET AJAX Se...
    - User and Role Management for an ASP.NET AJAX...
    - Programming an ASP.NET AJAX Server-Centric B...

    Iron Speed




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway