Database Code
  Home arrow Database Code arrow Chapter 6 Objects Have Class Reference Hav...
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? 
DATABASE CODE

Chapter 6 Objects Have Class Reference Have Type
By: aspfree
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 2
    2002-10-17

    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


    I must admit that my first exposure to object oriented programming (OOP) was frustrating and difficult. As a hobbyist I have struggled through Z80 assembly and EPROM burners, BASIC, Turbo Pascal, Java, C++ COM and now C#. The move to event driven programming and then to object oriented programming presented major conceptual hurdles to my function driven sequential programming mindset. The “aha” moment when OOP made sense was most gratifying, but did not come quickly or easily.Louie
    10/27/2002

    It has been a few years since I “got” the OOP mindset and I feel comfortable enough now to try to help fellow travelers with this journey. If OOP comes easily to you, feel free to skip this tutorial. If you are having problems getting your mind around objects and inheritance I hope this tutorial can help you. This tutorial does not represent a conventional teaching method. It assumes a passing knowledge of the C# language and familiarity with the Visual Studio .NET IDE. This is a work in progress and may require correction or revisions. 

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

    Useful Texts 

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

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

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

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

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

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

    Chapter 6 "Objects Have Class, References Have Type" 

    Well, you have arrived. If you have survived to this point, you are beginning to realize both the power and complexity of programming using objects and inheritance. Much of the confusion about references, types, classes and objects is simplified by the following statement "Objects have class, references have type." The more technically correct version may be "Objects have class, reference variables have type." As long as it is understood that reference variables "contain" references to objects, the former statement is a superior in its simplicity.

    What is a Type? 

    There are a number of definitions of a type, but I have struggled to find an illuminating statement.  

     According to Grady Booch (Object Oriented Analysis and Design) type is "The definition of the domain of allowable values that an object may possess and the set of operations that may be performed upon the object. The terms class and type are usually (but not always) interchangeable; a type is a slightly different concept than a class, in that it emphasizes the importance of conformance to a common protocol... Typing lets us express our abstractions so that the programming language in which we implement them can be made to enforce design decisions." 

    According to Bertrand Meyer (Object-Oriented Software Construction) "A type is the static description of certain dynamic objects: the various data elements that will be processed during execution of a software system...The notion of type is a semantic concept, since every type directly influences the execution of a software object by defining the form of the objects that the system will create and manipulate at run time." 

    According to the "Gang of Four" (Design Patterns) "The set of all signatures defined by an object's operations is called the interface to the object...  A type is a name used to denote a particular interface.... An object may have many types, and widely different objects can share a type.... An object's interface says nothing about its implementation--different objects are free to implement requests differently."

    It is the last definition that emphasizes the concept of programming to an interface, one or more public views of an object. You can look at an interface as a contract between the designer of the class and the caller of the class. The interface determines what public fields and methods are visible to a caller of a class. C# provides direct support for "design by contract" with the key word interface.  In C#, a class can inherit multiple interfaces and a single implementation hierarchy. Thus a class can contain one or more distinct public contracts. Both Booch and Meyer allude to the fact that types allow the compiler to enforce design decisions and influence the execution of software. Why is this so important? The answer is that references imply restricted access.

    References Have Type

    You will recall that methods and properties of an object have access modifiers such as public, protected and private. The calling context and access modifiers determine the visibility of fields and methods of an object. Thus, public fields and methods are visible to callers outside of the class. However, there is another level of access control that is much more difficult to grasp and explain. In a nutshell, when you declare a reference variable, the type of the reference variable restricts access to one of the object's public contracts

    You use a reference variable to touch an object's fields and properties. The key concept is that the type of the reference variable determines which of the objects public contracts (interfaces) is accessible using the reference variable. If an object had only one distinct public contract, this discussion would be moot. But in fact an object can have many public contracts. For instance, every object in the C# framework derives from the base class Object. Lets look again at the inheritance hierarchy for TextBox:

    System.Object
       System.Web.UI.Control
          System.Web.UI.WebControls.WebControl
             System.Web.UI.WebControls.TextBox

    The TextBox control inherits from WebControl which inherits from Control which inherits from Object. Each of these four classes defines an interface or public view, a type. If you declare a reference variable of type Object, only the public members defined in System.Object are visible using the reference variable.

    object tb= new TextBox();

    If you use the Visual Studio IDE and enter "tb." the IDE will automatically display the only four methods that can be touched using "tb":

    Equals()
    GetHashCode()
    GetType()
    ToString()

    Thus the type of the reference variable "tb", object, limits access to a subset of the public methods and fields of the instance of class TextBox. Only one of the many public interfaces can be touched with the reference variable "tb".  You could also declare "tb" as type Control:

    Control tb= new TextBox();

    Now if you enter "tb.", a larger number of public fields and methods are automatically displayed by the IDE including:

    Equals()
    GetHashCode()
    GetType()
    ToString()
    ...
    DataBind()
    Dispose()

    Finally, if you declare a reference variable of type TextBox all of the public fields and members of the class TextBox are visible using the reference variable "tb" including:

    Equals()
    GetHashCode()
    GetType()
    ToString()
    DataBind()
    Dispose()
    ...

    Text

    All I can suggest is try it! Declare the variable "tb" using different types and see how the type of the reference variable restricts access to the public interface of the object. Note that an object's set of possible interfaces (types) can be defined by the objects class hierarchy as in the preceding example or through inheritance of multiple  interfaces. For example, here is the declaration of the class Hashtable that implements six distinct interfaces:

    public class Hashtable : IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable

    IEnumerable hash=new Hashtable();

    The reference variable hash is of type IEnumerable and is restricted to the public methods and fields of the IEnumerable Interface and System.Object:

    Equals()
    GetHashCode()
    GetType()
    ToString()
    GetEnumerator()

    Objects Have Class

    Well this should be pretty self explanatory. Remember, an object is an instance of a class and goes on the heap. A local reference variable goes on the stack and is used to touch an object.  The full interface of the object is defined in the class so an object has class. The object variable, on the other hand, is restricted by its type and can only be used to touch fields and properties defined in its type (or in System.Object). The compiler enforces the design decisions. Be clear, when you created a reference variable of type object in the previous example, you still created an instance of class TextBox on the heap.

    object tb= new TextBox();

    This line of code creates a local reference variable of type object on the stack and an object of class TextBox on the heap. 

    Casting About

    Since you can only touch an object using a reference variable, at times the need arises to change the type of a reference variable. You can do this by "casting" the type of a reference variable to another valid type. The type of the variable must be in the domain of types (public interfaces) defined by the class of the object. If you try to cast an object variable to a type that is not supported by the class of the object, a runtime exception will be thrown. "Casting up" the class hierarchy from a subtype to a base type is always safe. The converse is not true. "Casting down" the class hierarchy is not always safe and result in a runtime InvalidCastException. Here is an example of casting down the class hierarchy:

    object tb= new TextBox();
    ((TextBox)tb).Text= "Hello";

    By explicitly casting the reference variable to the type TextBox, you are telling the compiler that you want to access the full interface of the class TextBox. A more common task is create another reference variable like this:

    TextBox textBox= (TextBox)tb;

    This creates a separate local reference variable on the stack of type TextBox. Both variables, "tb" and "textBox", contain references to the same object on the heap of class TextBox, but each variable has a different type and hence different access to the public fields and methods of the single object on the heap.

    A Twisted Analogy

    Now if this is just not making sense to you, let me try a twisted analogy of types. Just as an object can have different public views, a complex person can wear different "hats" or play different roles in life. A complex person can have multiple defined roles or types. When a complex person is wearing the "hat" of say a police officer, he or she is restricted by the implied contract between the clients (the populace) and the role of a police officer. When in uniform, the complex person has a type of police officer. When that same complex person goes home, he or she may put on the "hat" of a parent and is expected to exhibit behavior consistent with the role of a parent. At home, off duty, the complex person is expected to have the type of a parent. In an emergency, the off duty complex person is expected to assume the role of a police officer. You can "cast" an off duty officer of type parent to a police officer. You should not cast a twisted programmer of type parent to the type police officer. This will definitely result in a runtime exception!

    IS and AS

    Since casting down the class hierarchy is not "safe", you must code defensively. The C# language provides the key words is and as which greatly simplifies writing exception safe code. The key word is returns true if the object referred to by the left sided operand supports the type of the right sided operand. According to the IDE:

    The is operator is used to check whether the run-time type of an object is compatible with a given type. The is operator is used in an expression of the form:

    expression is type

    Where:

    expression
    An expression of a reference type.
    type
    A type.

    Remarks

    An is expression evaluates to true if both of the following conditions are met:

    • expression is not null.
    • expression can be cast to type. That is, a cast expression of the form (type)(expression) will complete without throwing an exception. For more information, see 7.6.6 Cast expressions .

    A compile-time warning will be issued if the expression expression is type is known to always be true or always be false.

    The is operator cannot be overloaded.

    Here is an example using is:

    private TextBox Cast(object o) 
    {
    if (o is TextBox) 
    {
    return (TextBox)o;
    }
    else 
    {
    return null;
    }
    }
    object tb= new TextBox();
    TextBox textBox= Cast(tb);

    In this sample using is, if the cast is invalid the result is null. Alternatively, you can use the key word as. According to the IDE:

    The as operator is used to perform conversions between compatible types. The as operator is used in an expression of the form:

    expression as type

    where:

    expression
    An expression of a reference type.
    type
    A reference type.

    Remarks

    The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. More formally, an expression of the form:

    expression as type

    is equivalent to:

    expression is type ? (type)expression : (type)null

    except that expression is evaluated only once.

    As in the previous example using is, if the cast is not valid, the result is null. I prefer using is. I would argue that code using is, is more readable than code using as.

    Well I hope this discussion of references, types, classes and objects has clarified things for you.  In a nutshell, when you declare a reference variable, the type of the reference variable restricts access to one of the object's public contracts. When in doubt, repeat the mantra "Objects have class, references have type."

    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 Database Code Articles
    More By aspfree

     

    IBM® developerWorks developerWorks - FREE Tools!


    Build Forge Express demo: Enabling software delivery excellence for small and midsized businesses

    This demonstration gives you an overview of IBM® Rational® Build Forge Express Edition, a global offering that provides a framework to automate and execute software processes. Rational Build Forge provides a software assembly line that can support all of your tools, technologies, and platforms so you can achieve a repeatable, reliable, and traceable build and release process.
    FREE! Go There Now!


    Check out the new Jazz space on developerWorks

    <a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts.
    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 Business Developer V7.1

    Visit IBM developerWorks to download a free trial version of IBM Rational Business Developer V7.1. Rational Business Developer offers rapid and simplified development of business applications and services through Enterprise Generation Language (EGL) tools, generating Java or mainframe solutions while shielding developers from technical complexities.
    FREE! Go There Now!


    NEW! Hacking 101

    Join us for this web seminar to learn how you can defend your web applications from attack. Learn about the 3 most common web application attacks, including how they occur and what can be done to prevent them. We’ll also discuss manual versus automated approaches for scanning and identifying web application vulnerabilities and how IBM Rational AppScan, an automated vulnerability scanner, can help you automate more of what you are doing manually today.
    FREE! Go There Now!


    NEW! Hello World: Learn how to install and use the Rational Asset Manager Eclipse client

    In this tutorial, you can learn how to install and configure the IBM Rational Asset Manager Eclipse client, explore the different views in the Asset Management perspective, learn various search techniques, work with existing assets, and submit a new asset.
    FREE! Go There Now!


    NEW! IBM Rational AppScan Standard Edition V7.7

    Secure your Web applications with IBM Rational AppScan Standard Edition V7.7, previously known as Watchfire AppScan. This Web application security testing tool automates vulnerability assessments and scans and tests for common Web application vulnerabilities. Visit IBM developerWorks to download a free trial of IBM Rational AppScan Standard Edition V7.7.
    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! Maintaining QoS and Process Integrity in an SOA Environment

    This webcast outlines the best practices that must be instituted to gain the maximum benefit from SOA while maintaining high quality of service. Whether you are deploying new applications or managing and monitoring your existing infrastructure, learn how you can ensure high quality of services with SOA based solutions from IBM. All registrants who attend this live Web Seminar will receive complimentary access to a white paper titled “Maintaining QoS in an SOA Environment”.
    FREE! Go There Now!


    NEW! Successful Change and Release Management for .NET

    Join this webcast to discover the key requirements for successful change and release management. Learn how to extend your .NET environment to improve productivity and collaboration, and address core problems afflicting team development. In this webcast, we’ll review typical challenges faced by customers and how to resolve them with the IBM Rational Change and Release Management solution, including Rational ClearCase, Rational ClearQuest and Rational Build Forge. Replay is available for 9 months.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    DATABASE CODE ARTICLES

    - Deployment of the MobiLink Synchronization M...
    - MobiLink Synchronization Wizard in SQL Anywh...
    - Finding Matching Records in Data Access Pages
    - Using the AccessDataSource Control in VS 2005
    - A Closer Look at ADO.NET: The Command Object
    - A Closer Look at ADO.NET: The Connection Obj...
    - Using ADO to Communicate with the Database, ...
    - Code Snippets: Counting Records
    - Constraints In Microsoft SQL Server 2000
    - Multilingual entries into a DB and to be dis...
    - Getting A List of Tables From SQL Server
    - SQL Server Database Creator - .NET Version
    - ADO Recordset Paging
    - Two combos, one textbox example
    - Discussion & Listserv Module by Mike Eck...





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