Pages

Monday, October 13, 2008

intro

Introduction

Object-Oriented Programming (OOP) is a software development paradigm that suggests developers to split a program in building blocks known as objects. The OOP paradigm allows developers to define the object's data, functions, and its relationship with other objects.

Microsoft created the .NET Framework using OOP, and knowing this concepts has helped me to understand the .NET Framework and to design and develop better software components. The purpose of this article is to describe the basic OOP concepts using real world scenarios and to provide some code samples that demonstrate how to work with OOP and .NET.

Class

The most common definition states that a class is a template for an object. Suppose that someone builds a paper pattern for a shirt. All the shirts done with the same paper pattern will be identical (same design, size, etc.). In this sample, the paper pattern is the class and the shirt is the object. To build the same exact shirt over and over, you need the paper pattern as a template. Another great example are house plans and blueprints. The plans and blueprints define the number of rooms, the size of the kitchen, the number of floors, and more. In this real world sample, the house plans and blueprints are the class and the house is the object. In OOP you program a class as a template for a specific object or groups ob objects that will always have the same features.

Class members

A class has different members, and developers in Microsoft suggest to program them in the following order:

* Namespace: The namespace is a keyword that defines a distinctive name or last name for the class. A namespace categorizes and organizes the library (assembly) where the class belongs and avoids collisions with classes that share the same name.
* Class declaration: Line of code where the class name and type are defined.
* Fields: Set of variables declared in a class block.
* Constants: Set of constants declared in a class block.
* Constructors: A method or group of methods that contains code to initialize the class.
* Properties: The set of descriptive data of an object.
* Events: Program responses that get fired after a user or application action.
* Methods: Set of functions of the class.
* Destructor: A method that is called when the class is destroyed. In managed code, the Garbage Collector is in charge of destroying objects; however, in some cases developers need to take extra actions when objects are being released, such as freeing handles or deallocating unmanaged objects. In .NET, there is no concept of deterministic destructors. The Garbage Collector will call the Finalize() method at a non-deterministic time while reclaiming memory for the application.

Access keywords

Access keywords define the access to class members from the same class and from other classes. The most common access keywords are:

* Public: Allows access to the class member from any other class.
* Private: Allows access to the class member only in the same class.
* Protected: Allows access to the class member only within the same class and from inherited classes.
* Internal: Allows access to the class member only in the same assembly.
* Protected internal: Allows access to the class member only within the same class, from inherited classes, and other classes in the same assembly.
* Static: Indicates that the member can be called without first instantiating the class.

The following sample code illustrates a sample class in C#:

/// C#
///Imported namespaces
using System;
/// Namespace: Consider using CompanyName.Product.ComponentType
namespace DotNetTreats.OOSE.OOP_CSharp
{
///Class declaration
public class employee
{
///Fields
private string _name;
private int _salary;
///Constants
private const int anualBonus = 1000;
///Constructor
public employee()
{
}
///Properties
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public int Salary
{
get
{
return _salary;
}
set
{
_salary = value;
}
}
/// Event handlers
public event EventHandler OnPromotion
{
add
{
}

remove
{
}
}
/// Methods
public void DuplicateSalary()
{
_salary = _salary*2;
}
}
}

Listing 1. Sample class implementation in C#

The following sample code illustrates a sample class in VB.NET:

' VB.NET
'Imported namespaces
Imports System
' Namespace: Consider using CompanyName.Product.ComponentType
Namespace DotNetTreats.OOSE.OOP_VBNET
'Class declaration
Public Class employee
'Fields
Private _name As String
Private _salary As Integer
'Constants
Private Const anualBonus As Integer = 1000
'Constructors
Public Sub New()
MyBase.New()
End Sub
'Properties
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal Value As String)
_name = value
End Set
End Property
Public Property Salary() As Integer
Get
Return _salary
End Get
Set(ByVal Value As Integer)
_salary = value
End Set
End Property
' Event handlers
Public Event OnPromotion As EventHandler
'Methods
Public Sub DuplicateSalary()
_salary = (_salary * 2)
End Sub
End Class
End Namespace

Listing 2. Sample class implementation in VB.NET

Object

Objects are the building blocks of OOP and are commonly defined as variables or data structures that encapsulate behavior and data in a programmed unit. Objects are items that can be individually created, manipulated, and represent real world things in an abstract way.

Object composition

Every object is composed by:

* Object identity: Means that every object is unique and can be differentiated from other objects. Each time and object is created (instantiated) the object identity is defined.
* Object behavior: What the object can do. In OOP, methods work as functions that define the set of actions that the object can do.
* Object state: The data stored within the object at any given moment. In OOP, fields, constants, and properties define the state of an object.

Structures

Not everything in the real world should be represented as a class. Structures are suitable to represent lightweight objects. Structures can have methods and properties and are useful for defining types that act as user-defined primitives, but contain arbitrary composite fields. The .NET Framework defines some structures such as System.Drawing.Rectangle, System.Drawing.Point, and System.Drawing.Color.

The following code sample represents a structures in C#:

/// C#
struct Point
{
private int _x;
private int _y;
Point(int x, int y)
{
this._x = x;
this._y = y;
}
public int X
{
get
{
return _x;
}
set
{
_x = value;
}
}
public int Y
{
get
{
return _y;
}
set
{
_y = value;
}
}
}

Listing 3. Sample structure implementation in C#

The following code sample represents a structure in VB.NET:

' VB.NET

Structure Point
Private _x As Integer
Private _y As Integer
Sub New(ByVal x As Integer, ByVal y As Integer)
MyBase.New()
Me._x = x
Me._y = y
End Sub
Public Property X() As Integer
Get
Return _x
End Get
Set(ByVal Value As Integer)
_x = value
End Set
End Property
Public Property Y() As Integer
Get
Return _y
End Get
Set(ByVal Value As Integer)
_y = value
End Set
End Property
End Structure

Listing 4. Sample structure implementation in VB.NET

Conclusion

OOP is full of abstract concepts, and the best approach to understand them is practical and not only theoretical. I learned more OOP after making some designs and after implementing some components. The concepts presented in this article might clarify the meaning, but I strongly recommend to go and have fun playing around with OOP. In this article, I examined the concept of classes, objects, and structs. The second part will examine the concepts of inheritance, abstraction, and polymorpIn Part 1 of Object-Oriented Programming Concepts and .NET, I defined the concepts of class, object, and structure. In addition to defining the concepts, I explained real world samples and presented sample code in C# and VB.NET to create classes and structs. The first article also explains objects as independent building blocks.

In Part 2 of Object-Oriented Programming Concepts and .NET, I will explain the concepts of inheritance, abstraction, and polymorphism. I will also present a Unified Model Language (UML) class diagram to represent an object model that will help as a visual aid to explain some concepts. The purpose of this article is to explain a series of relationships between objects.

Inheritance

In the real world there are many objects that can be specialized. In OOP, a parent class can inherit its behavior and state to children classes. This concept was developed to manage generalization and specialization in OOP and is represented by a is-a relationship.

The following OO terms are commonly used names given to parent and child classes in OOP:

* Superclass: Parent class.
* Subclass: Child class.
* Base class: Parent class.
* Derived class: Child class

The most common real world sample to explain inheritance is the geometric shapes object model. Squares, circles, triangles, rectangles, pentagons, hexagons, and octagons are geometric shapes. The following figure shows a sample set of geometric figures:



Figure 1. Geometric shapes.

The concept of generalization in OOP means that an object encapsulates common state an behavior for a category of objects. The general object in this sample is the geometric shape. Most geometric shapes have area, perimeter, and color. The concept of specialization in OOP means that an object can inherit the common state and behavior of a generic object; however, each object needs to define its own special and particular state an behavior. In Figure 1, each shape has its own color. Each shape has also particular formulas to calculate its area and perimeter.

Inheritance makes code elegant and less repetitive. If we know that all shapes have color, should we program a color attribute for each shape? The answer is no! Would it be a better idea to create a shape class that has a color attribute and to make all the specialized shapes to inherit the color attribute? The answer is yes!

An object model for this sample could have a shape parent class and a derived class for each specific shape. The following UML class diagram shows the set of classes needed to model the geometric shapes sample. Observe the field, properties, and methods for each class:

Figure 2. The Shape class is the parent class. Square, Rectangle, and Circle are derived classes that inherit from Shape. The triangle-connector in the diagram represents an is-a relationship.

The .NET framework has many base classes. Everything is derived from System.Object. You can create almost anything you imagine using the built-in functionality provided in the .NET Framework Class Library.

To create a derived class in C#, the class declaration should be done as:

class child: parent

To create a derived class in VB.NET, the class declaration should be done as:

Class child
Inherits parent
End Class


Multiple inheritance

Multiple inheritance is the possibility that a child class can have multiple parents. Human beings have always two parents, so a child will have characteristics from both parents.

In OOP, multiple inheritance might become difficult to handle because it allows ambiguity for the compiler. There are programming languages such as C++ that allow multiple inheritance; however, other programming languages such as Java and the .NET Framework languages do not allow multiple inheritance. Multiple inheritance can be emulated in .NET using Multiple Interface Inheritance, which I will explain in Part 3 of this series.

Sealed class

A sealed class is a class that does not allow inheritance. Some object model designs need to allow the creation of new instances but not inheritance, if this is the case, the class should be declared as sealed.

To create a sealed class in C#, the class declaration should be done as:

sealed class Shape

To create a sealed class in VB.NET, the class declaration should be done as:

NonInheritable Class Shape

Abstraction

Abstraction is "the process of identifying common patterns that have systematic variations; an abstraction represents the common pattern and provides a means for specifying which variation to use" (Richard Gabriel).

An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes contain one or more abstract methods that do not have implementation. Abstract classes allow specialization of inherited classes.

Figure 2 shows a Shape class, which is an abstract class. In the real world, you never calculate the area or perimeter of a generic shape, you must know what kind of geometric shape you have because each shape (eg. square, circle, rectangle, etc.) has its own area and perimeter formulas. The parent class shape forces all derived classes to define the behavior for CalculateArea() and CalculatePerimeter(). Another great example is a bank account. People own savings accounts, checking accounts, credit accounts, investment accounts, but not generic bank accounts. In this case, a bank account can be an abstract class and all the other specialized bank accounts inherit from bank account.

To create an abstract class in C#, the class declaration should be done as:

abstract class Shape

To create an abstract class in VB.NET, the class declaration should be done as:

MustInherit Class Shape

To following code shows a sample implementation of an abstract class:

/// C#
using System;
namespace DotNetTreats.OOSE.OOPSamples
{
public abstract class Shape
{
private float _area;
private System.Drawing.Color _color;
private float _perimeter;
public float Area
{
get
{
return _area;
}
set
{
_area = value;
}
}
public System.Drawing.Color Color
{
get
{
return _color;
}
set
{
_color = value;
}
}
public float Perimeter
{
get
{
return _perimeter;
}
set
{
_perimeter = value;
}
}
public abstract void CalculateArea();
public abstract void CalculatePerimeter();
}
}

Listing 1. The Shape abstract class in C#.

Polymorphism

Polymorphism allows objects to be represented in multiple forms. Even though classes are derived or inherited from the same parent class, each derived class will have its own behavior. Polymorphism is a concept linked to inheritance and assures that derived classes have the same functions even though each derived class performs different operations.

Figure 2 shows a Rectangle, a Circle, and Square. All of them are shapes and as shapes their area and perimeter can be calculated; however, each shape calculates its area in a specialized way. Declaring a member as abstract allows polymorphism. The Shape class defines the CalculateArea() and CalculatePerimeter() methods as abstract, this allows each derived class to override the implementation of the parent's methods.

To following sample code shows an implementation of a derived class (rectangle). The specific CalculateArea() and CalculatePerimeter() methods for the rectangle class illustrate polymorphism:

/// C#
using System;
namespace DotNetTreats.OOSE.OOPSamples
{
class Rectangle : Shape
{
private float _height;
private float _width;
public rectangle(float height, float width)
{
_height = height;
_width = width;
}
public float Height
{
get
{
return _height;
}
set
{
_height = value;
}
}
public float Width
{
get
{
return _width;
}
set
{
_width = value;
}
}
public override void CalculateArea()
{
this.Area = _height * _width;
}
public override void CalculatePerimeter()
{
this.Perimeter = (_height * 2) + (_width * 2);
}
}
}

Listing 2. Polymorphism represented in the Rectangle's methods.

Virtual keyword

The virtual keyword allows polymorphism too. A virtual property or method has an implementation in the base class, and can be overriden in the derived classes.

To create a virtual member in C#, use the virtual keyword:

public virtual void Draw()

To create a virtual member in VB.NET, use the Overridable keyword:

Public Overridable Function Draw()

Override keyword

Overriding is the action of modifying or replacing the implementation of the parent class with a new one. Parent classes with virtual or abstract members allow derived classes to override them.

To override a member in C#, use the override keyword:

public override void CalculateArea()

To override a member in VB.NET, use the Overrides keyword:

Public Overrides Function CalculateArea()

Conclusion

Inheritance allows developers to manage a generalization and specialization relationship between objects. OOP concepts such as abstraction and polymorphism help to define better object models where object hierarchies are designed with reusability in mind. In this article, I examined the concept of inheritance, abstraction, and polymorphism. The third and last part of this series will examine the concepts of interface, multiple interface inheritance, collections, and overloading.

Note: The sample source code* for this article works only in Visual Studio 2005.

0 comments: