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  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
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


    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! Addressing software-as-a-service challenges using Tivoli security and WebSphere solutions

    Building a software-as-a-service solution requires addressing a few key technical challenges. In this webcast, we'll focus on the role of IBM Tivoli Directory Server and WebSphere Portlet Factory in creating a Software as a Service solution. We will demonstrate how to use Tivoli Directory Server to prevent the user population of one tenant from accessing the virtual portal and portlet components of another tenant. We will also use the dynamic profile capability of WebSphere Portlet Factory to create multiple highly customized applications from one code base.
    FREE! Go There Now!


    NEW! Application Development Tools for the Mainframe Developer

    You probably have thousands of lines of COBOL code loaded with business intelligence and being used to run your business, along with an army of developers maintaining these applications. Learn how to prepare your applications and developers so you can keep that competitive edge and move to a service-oriented architecture with the IBM Rational Enterprise Modernization solutions. Replay is available for 9 months.
    FREE! Go There Now!


    NEW! Download IBM Data Studio V1.1

    Visit IBM developerWorks to download the latest trial version of IBM Data Studio V1.1 at no cost. IBM Data Studio is a comprehensive data management solution that helps you effectively design, develop, deploy and manage your data, databases, and database applications throughout the data management life cycle utilizing a consistent and integrated user interface. Unlike other client-side data management solutions that focus on only one aspect of the application lifecycle or database administration, Data Studio complements the Rational Software Delivery platform, providing unparalleled flexibility for a heterogeneous data server environment across platforms.
    FREE! Go There Now!


    NEW! Evaluate Rational Host Access Transformation Services (HATS) Toolkit V7.1

    Visit IBM developerWorks to download a free trial of the Rational Host Access Transformation Services (HATS) Toolkit. The HATS toolkit provides a set of plug-ins for the IBM Rational Software Delivery Platform to help you easily extend your legacy applications. HATS makes your 3270 and 5250 applications available as HTML through the most popular Web browsers, while converting your host screens to a Web look and feel and it also enables you to develop new Web, portal, and rich-client applications.
    FREE! Go There Now!


    NEW! Info 2.0: Harnessing the power of Web 2.0 and Enterprise Mashups

    Listen to this webcast to get an overview of Info 2.0 and a technical demo of how to quickly build an enterprise mashup. IBM's Info 2.0 technology leverages emerging Web 2.0 technologies such as mashups, feeds, AJAX, and JSON in order to simplify assembly of information using feeds and services. Come learn about the technical elements of Info 2.0 including the Feed Generation framework, Mashup Engine, and mashup assembly components. Learn how to pull information from databases, departmental information, and the Web to create mashups critical to your company’s success. We will also discuss best practices to help you get started.
    FREE! Go There Now!


    NEW! Trial download: IBM Lotus Forms V3.0

    Get a free trial download of IBM Lotus Forms V3.0 (formerly Workplace Forms), which provides a zero-footprint eForms solution to help you automate and move forms-based business processes off the desktop and onto the Web. With Lotus Forms, you can extend applications beyond the firewall by creating a single electronic form document ready for use in both thick and Web 2.0 thin client format.
    FREE! Go There Now!


    NEW! Trial download: IBM Rational Method Composer V7.2

    Get a free trial download of the latest version of IBM Rational Method Composer V7.2 which helps you deliver customized yet consistent process guidance to your project teams and IT organization, and includes the latest version of IBM Rational Unified Process (RUP), which has provided process guidance to teams since 1996.
    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! Using IBM Rational Developer for System z and IBM Rational ClearCase together to manage application development

    Whether you are creating new applications or modifying existing ones, managing integration of new components with traditional z/OS elements is a critical part of building and deploying modern applications. Listen to this webcast to see how IBM can help you optimize your development process using an IDE like Rational Developer for System z that integrates with management tools, such as ClearCase to manage your application development on mainframes.
    FREE! Go There Now!


    Refresh! IBM Rational Systems Development Solution eKit

    With IBM Rational Systems Development Solution, you can deliver products faster with higher quality. Within this kit, Read the “Model Driven Systems Development” white paper to see how to improve product quality and communication. Then check out the rest of the e-Kit to learn more about important topics that can affect the success of any software project through customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems. From start to finish, at every stage in your projects, Rational Systems Development Solution can help your company reach its full potential.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    ASP.NET ARTICLES

    - How to Test a Web Application
    - How to Add Code and Validation Controls to a...
    - Working in Source and Split Views to Build a...
    - How to Build a Web Form for a One-Page Web A...
    - How to Develop a One-Page Web Application
    - An ASP.NET Web Application in Action
    - Developing ASP.NET Web Applications
    - An Introduction to ASP.NET Web Programming
    - Introduction to the ADO.NET Entity Framework...
    - Completing an In-Text Advertising System und...
    - Programming an In-Text Advertising System un...
    - Building an In-Text Advertising System Under...
    - Developing a Mini ASP.NET AJAX Server Centri...
    - Disadvantages of the ASP.NET MVC Framework
    - Advantages of the ASP.NET MVC Approach





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