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. 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).[bold]Useful Texts[/bold]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![bold]Object-Oriented Analysis and Design with Applications Grady Booch, Second Edition, Addison-Wesley, 1994, 589pp.[/bold][bold]Design Patterns Elements of Reusable Object-Oriented Software Gamma Helm, Johnson and Vlissides, Addison-Wesley, 1994, 395pp.[/bold][bold]Object-Oriented Software Construction Second Edition Bertrand Meyer, Prentice Hall, 1997, 1254pp.[/bold]Of course, some of this material is a descendent of my writing from our now out of print book: [bold]Visual Café for Java Explorer Database Development Edition Brogden Louie and Tittle, Coriolis, 1998, 595pp.[/bold]- Chapter 1 "Classes, Objects, and Properties" -[bold]Why program with objects and inheritance?[/bold] Simply put, programming with objects simplifies the task of creating and maintaining complex applications. OOP is a completely different way of thinking that differs significantly from the more traditional function driven sequential programming model of old. Programming with objects without inheritance is ?object-based? programming. Adding inheritance to objects is ?object-oriented? programming. OOP provides built in support for code reuse (inheritance) and support for runtime variations in program behavior (polymorphism). Without attempting to define these terms, OOP at a minimum:1. Simplifies the creation and maintenance of complex applications. 2. Promotes code reuse. 3. Allows flexibility in runtime program behavior (a very cool feature). [bold]What is OOP?[/bold]Well, lets cut right to the point. What the heck is Object Oriented Programming? Answer: It is a whole new way of thinking about programming! It is a way of modeling software that maps your code to the real world. Instead of creating programs with global data and modular functions, you create programs with ?classes?. A class is a software construct that maps to real world things and ideas. Think of a class as a blueprint that contains information to construct a software object in memory. Unlike a simple data structure, software objects contain code for both data and methods. The class binds the data and methods together into a single namespace so that the data and methods are intertwined.Just as you can build more than one house from a single blueprint, you can construct multiple software objects from a single class. Each object (represented by code in memory) is generated from a class and is considered an ?instance? of the class. Since each instance of the class exist in separate memory space, each instance of the class can have its own data values (state). Just as multiple houses built from a single blueprint can differ in properties (e.g. color) and have identity (a street address), multiple objects built from a single class can differ in data values and have a unique identifier (a C++ pointer or a reference handle in C#). Got that! Now take and break and re-read this paragraph. When you come back, you can look at some C# code.[bold]What is a class?[/bold]A class is a software construct, a blueprint that can describe both values and behavior. It contains the information needed to create working code in memory. When you create an object, you use the information in the class to generate working code. Let?s create a simple program that models a toaster! The toaster is a real life object. The toaster can have state such as secondsToToast and has a behavior, MakeToast(). Here is our first toaster class in C#:
class Toaster1 { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { // // TODO: Add code to start application here // Toaster1 t= new Toaster1(); System.Console.WriteLine(t.MakeToast()); System.Console.ReadLine(); } private int secondsToToast= 10; public string MakeToast() { return "Toasted for "+secondsToToast.ToString()+" seconds."; } }
If you execute this program, the output is:?Toasted for 10 seconds.?A working toaster yes, but not very useful unless you like 10-second toast .[bold]What is an object?[/bold]An object is an instance of a class. A specific class describes how to create a specific object in memory. So the class must contain information about the values and behaviors that each object will implement. You can create an object using the reserved word ?new?. In our Toaster1 application, you create a single instance of the Toaster1 class with the call: Toaster1 t = new Toaster1();
The reference variable ?t?, now contains a reference to a unique instance of the Toaster1 class. You use this reference variable to ?touch? the object. In fact, if you set the reference variable ?t? to null, so that the object is no longer ?touchable?, the garbage collector will eventually delete the Toaster1 object! t = null;
// If "t" contains the only reference to the Toaster1 object, the object can be garbage collected. (Strictly speaking, if the Toaster1 object cannot be "reached", it can be garbage collected.)
MakeToast() is a public method of the Toaster1 object so it can be called from outside the class (Main) using the reference variable ?t? to touch the object?s behavior: t .MakeToast();
Since each object exists in a separate memory space, each object can have state, behavior and identity. Our Toaster1 object has identity since it is unique from any other object created from the Toaster1 class: Toaster1 t2 = new Toaster1();
Now there are two instances of the Toaster1 class. There are two reference variables ?t? and ?t2?. Each reference variable identifies a unique object that exists in a separate memory address. Since each object contains a method MakeToast(), each object has behavior. Finally, each object contains a value ?secondsToToast()?. In a sense, each object now has its own ?state?. However, the state is the same for each object! This is not a very useful class design. In fact, the Toaster1 class is not a good representation of a real world toaster since the toast time is immutable. Here is a second run at the Toaster class that demonstrates the use of public ?accessors?, get and set methods. This is a standard idiom in OOP. The actual data is declared private (or protected) so that users of the class cannot access the underlying data. Instead, public methods are exposed to the callers of the class to set and get the underlying hidden data values.Note: The modifiers ?private?, ?protected? and ?public? are access modifiers that control the visibility of methods and data. The compiler will enforce these visibility rules and complain if you say try to touch a private variable from outside the class. ?Public? methods and data are visible to any caller. ?Private? methods and data are only visible and ?touchable? within the class. ?Protected? is a special level of access control of great interest to object oriented programmers, but is a subject that must be deferred to the chapter on inheritance. If you don?t declare an access modifier, the method or variable is considered private by default. using System ;namespace JAL { /// <summary> /// Summary description for class. /// </summary> /// class Toaster2 { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { Toaster2 t= new Toaster2(); t.SetSecondsToToast(12); Console.WriteLine(t.MakeToast()); Console.ReadLine(); } private int secondsToToast= 0; public string MakeToast() { return "Toasted for "+GetSecondsToToast().ToString()+" seconds."; } // Public Accessor Functions, Get and Set public bool SetSecondsToToast(int seconds) { if (seconds > 0) { secondsToToast= seconds; return true; } else { secondsToToast= 0; return false; } } public int GetSecondsToToast() { return secondsToToast; } } }
The callers of the class cannot ?touch? the secondsToToast variable which remains private or ?hidden? from the caller. This idiom is often called ?encapsulation? so that the class encapsulates or hides the underlying data representation. This is an important aspect of OOP that allows the writer of the class to change the underlying data representation from say several variables of type int to an array of ints without affecting the caller. The class is a ?black box? that hides the underlying data representation. In this new version of toaster, Toaster2, there are two new methods: SetSecondsToToast() and GetSecondsToToast(). If you look at the ?setter? method it validates the callers input and sets the value to zero if the callers input is invalid (<0):
public void SetSecondsToToast(int seconds) { if (seconds > 0) { secondsToToast= seconds; } else { secondsToToast= 0; } }
The ?getter? method really does not do much simply returning the private data value ?secondsToToast?:
public int GetSecondsToToast() { return secondsToToast; }
[bold]What is a property?[/bold]C#.NET implements a language idiom called a ?property?. In a nutshell, ?a property is a method that appears as a variable?. By convention, a property name starts with an uppercase letter. Here is our new version of Toaster that replaces the get and set methods with properties: using System ;namespace JAL { /// <summary> /// Summary description for class. /// </summary> /// class Toaster3 { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { Toaster3 t= new Toaster3(); t.SecondsToToast= 12; // the property idiom Console.WriteLine(t.MakeToast()); Console.ReadLine(); } private int secondsToToast= 0; public string MakeToast() { return "Toasted for "+secondsToToast.ToString()+" seconds."; } // Properties public int SecondsToToast { get {return secondsToToast;} set { if (value > 0) { secondsToToast= value; } else { secondsToToast= 0; } } } } }
Here are the new setter and getter methods as properties: // Properties public int SecondsToToast { get {return secondsToToast;} set { if (value > 0) { secondsToToast= value; } else { secondsToToast= 0; } } }
The reserved word ?value? is used to represent the caller?s input. Note the syntax used to call a property. To set a property use: t .SecondsToToast= 12;
The method set() now appears as a variable ?SecondsToToast?. So ?a property is a method that appears as a variable?.Well, congratulations. You have constructed your first real world class in C#. Since this is a hands on tutorial, I strongly urge you to compile the Toaster3 code and experiment.[bold]All Rights Reserved Jeff Louie 2002[/bold]
| 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 Code Articles More By Jeff Louie developerWorks - FREE Tools! | 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!
| | | | You might know that you can pull XML data into OpenOffice's spreadsheet program, Calc, but did you know that you can create a filter to make word-processing documents out of data stored as XML? This tutorial shows you how to use OpenOffice's import/export filters to open your XML data as though it's just a plain document. From there, users can edit the document much more naturally and then save it back to its native format. You can also use this feature to easily turn your documents into XML data. FREE! Go There Now!
| | | | 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!
| | | | Rational Build Forge Express Edition is an automation framework that packages the latest enterprise-grade technologies into a reliable, flexible and robust configuration designed and priced specifically for small to midsize businesses. The new Rational Build Forge Express eKit provides you with valuable resources – including a case study, podcast, demo, and articles – to help you increase staff productivity, compress development cycles and deliver better software, fast. FREE! Go There Now!
| | | | Here's a fun way to learn about DB2! Learn or teach the basics of DB2 and relational database with an interactive game called The DB2 Detective Game. The game teaches relational database concepts and shows how technology can be applied to solving real-life problems (the game's theme is a crime investigation). This tutorial has been updated for DB2 9. FREE! Go There Now!
| | | | This paper is about the critical role that a discipline called integrated requirements management can play in helping to ensure that your business goals and IT investments are continuously aligned—whether you are sourcing, integrating, building or maintaining software. It also looks at ways that automated IBM Rational® products can work together to help you use requirements in the very best way. FREE! Go There Now!
| | | | 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!
| | | | 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!
| | | | The Eclipse SOA Tools Platform (STP) plug-in and Apache Tuscany simplifies services development through the use of the popular Eclipse development environment. Apache Tuscany has also been integrated with the STP to provide a Service Component Architecture (SCA) Java run time for the services you create, allowing you to annotate your service using the SCA standard and Apache Tuscany annotations. In this tutorial, you will see STP and Apache Tuscany in action, through the creation of a Remote Method Invocation (RMI) service. FREE! Go There Now!
| | | | 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!
| | | | All FREE IBM® developerWorks Tools! | |