Skip to main content

oops

OOP & C#


The skeleton of object - oriented programming is of course the concepts of class. This C# tutorial on OOPS explains classes and their importance in implementation of object oriented principles.
Any language can be called object oriented if it has data and method that use data encapsulated in items named objects. An object oriented programming method has many advantages, some of them are flexibility and code reusability.
All the programming languages supporting Object oriented Programming will be supporting these three main concepts:
1. Encapsulation
2. Inheritance
3. Polymorphism
Encapsulation in C#:
Encapsulation is process of keeping data and methods together inside objects. In this way developer must define some methods of object's interaction. In C# , encapsulation is realized through the classes. A Class can contain data structures and methods. Consider the following class.
________________________________________
public class Aperture
{
public Aperture()
{

}

protected double height;
protected double width;
protected double thickness;

public double GetVolume()
{
double volume = height*width*thickness;
if(volume<0)
return 0;
return volume;
}
}
________________________________________
In this example we encapsulate some data such as height, width, thickness and method GetVolume. Other methods or objects can interact with this object through methods that have public access modifier. It must be done using . operator.
Inheritance in C#:
In a few words, Inheritance is the process of creation new classes from already existing classes. The inheritance feature allows us to reuse some parts of code. So, now we have some derived class that inherits base class's members. Consider the following code snippet:
________________________________________
public class Door : Aperture
{
public Door() : base()
{

}

public bool isOutside = true;
}
________________________________________
As you see to inherit one class from another, we need to write base class name after : symbol. Next thing that was done in code Door () constructor also inherits base class constructor. And at last we add new private field. All members of Aperture class are also in Door class. We can inherit all the members that has access modifier higher than protected.
Polymorphism in C#:
Polymorphism is possibility to change behavior with objects depending of object's data type. In C# polymorphism realizes through the using of keyword virtual and override. Let look on the example of code:
________________________________________
public virtual void Out()
{
Console.WriteLine("Aperture virtual method called");
}
//This method is defined in Aperture class.
public override void Out()
{
Console.WriteLine("Door virtual method called");
}
________________________________________

Now we need to re-define it in our derived Door class. The usage of virtual methods can be clarified when we creating an instance of derived class from the base class:
Aperture ap = new Door();
ap.Out();
In such cases, the runtime keeps record of all the virtual function details in a table called VMT(Virtual Method Table) and then in runtime dynamically picks the correct version of the function to be used. Here it uses Out() method from derived class of course.
To compile the attached example you need to run .NET console and run the next command: csc filename.cs .



















Introduction

OOPS or Object Oriented Programming Concepts but some of the concepts have been always used in one or the other programming languages. For example you must have used structs in C which is a good example of encapsulation. There are four major pillar of OOPS. Let’s try to understand each one of them by taking some examples also:-
1.) Encapsulation
2.) Abstraction
3.) Polymorphism
4.) Inheritance
Encapsulation:-

Interview Definition:- Binding data and member functions together inside a single unit.
How to Encapsulate:- By creating types e.g Classes and Struct
Bu using encapsulation we can create out own custom types by reusing the existing or primitive types.
Abstraction:-

Abstraction defines way to abstract or hide your data and members from outside world. Simply speaking Abstraction is hiding the complexities of your class or struct or in a generic term Type from outer world. This is achieved by means of access specifiers.
Interview Definition: - Hiding the complexities of your type from outside world.
How to Abstract: - By using Access Specifiers
.Net has five access specifiers:-
Public -- Accessible outside the class through object reference.
Private -- Accessible inside the class only through member functions.
Protected -- Just like private but Accessible in derived classes also through member functions.
Internal -- Visible inside the assembly. Accessible through objects.
Protected Internal -- Visible inside the assembly through objects and in derived classes outside the assembly through member functions.
Let’s try to understand by a practical example:-
Interview Tip:-
The default access specifier for a class in internal. Mind it I mean class not class’s data members.

public class Class1
{
int i; //No Access specifier means private
public int j; // Public
protected int k; //Protected data
internal int m; // Internal means visible inside assembly
protected internal int n; //inside assembly as well as to derived classes outside assembly
static int x; // This is also private
public static int y; //Static means shared across objects
[DllImport("MyDll.dll")]
public static extern int MyFoo(); //extern means declared in this assembly defined in some other assembly
public void myFoo2()
{
//Within a class if you create an object of same class then you can access all data members through object reference even private data too
Class1 obj = new Class1();
obj.i =10; //Error can’t access private data through object.But here it is accessible.:)
obj.j =10;
obj.k=10;
obj.m=10;
obj.n=10;
// obj.s =10; //Errror Static data can be accessed by class names only
Class1.x = 10;
// obj.y = 10; //Errror Static data can be accessed by class names only
Class1.y = 10;
}
}

Now lets try to copy the same code inside Main method and try to compile
[STAThread]
static void Main()
{
//Access specifiers comes into picture only when you create object of class outside the class
Class1 obj = new Class1();
// obj.i =10; //Error can’t access private data through object.
obj.j =10;
// obj.k=10; //Error can’t access protected data through object.
obj.m=10;
obj.n=10;
// obj.s =10; //Errror Static data can be accessed by class names only
Class1.x = 10; //Error can’t access private data outside class
// obj.y = 10; //Errror Static data can be accessed by class names only
Class1.y = 10;
}
What if Main is inside another assembly
[STAThread]
static void Main()
{
//Access specifiers comes into picture only when you create object of class outside the class
Class1 obj = new Class1();
// obj.i =10; //Error can’t access private data through object.
obj.j =10;
// obj.k=10; //Error can’t access protected data through object.
// obj.m=10; // Error can’t access internal data outside assembly
// obj.n=10; // Error can’t access internal data outside assembly

// obj.s =10; //Errror Static data can be accessed by class names only
Class1.x = 10; //Error can’t access private data outside class
// obj.y = 10; //Errror Static data can be accessed by class names only
Class1.y = 10;
}



















Object-Oriented Programming Concepts and .NET
Part 2: Inheritance, Abstraction, and Polimorphism in .NET
Erika Ehrli Cabral
March 2005
Summary
The following article is the second of a three-part article series that presents definitions and samples for different Object-Oriented Programming (OOP) concepts and its implementation in .NET. The first part examined the concepts of classes, objects, and structures. This part examines the concepts of inheritance, abstraction, and polimorphism. The third and last part will examine the concepts of interface, multiple interface inheritance, collections, and overloading.
Contents
• Introduction
• Inheritance
• Abstraction
• Polimorphism
• Conclusion
• Reference
Introduction
In 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 polimorphism. 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:
NotInheritable 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#.
Polimorphism
Polimorphism 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. Polimorphism 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 polimorphism. 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 polimorphism:
/// 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. Polimorphism represented in the Rectangle's methods.
Virtual keyword
The virtual keyword allows polimorphism 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 polimorphism 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 polimorphism. The third and last part of this series will examine the concepts of interface, multiple interface inheritance, collections, and overloading.

Comments

Popular posts from this blog