OOPS


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.

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.

ClassThe most common definition states that a class is a template for an object.

  • While an instance of a class contains a separate copy of all instance fields of the class, there is only one copy of each static field.
  • It is not possible to use this to reference static methods or property accessors.
  • If the static keyword is applied to a class, all the members of the class must be static.
  • Classes, including static classes, may have static constructors. Static constructors are called at some point between when the program begins and the class is instantiated.
 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.
 Constructors
 A class can have any number of constructors but can have only one static constructor. constructors doesn't return any value. constructors are two types. one is static and another one is instance constructors (non-static). static constructors allows only static variables and shouldn’t take any parameters there should not be any access modifiers. the static constucots called only one time.
C# supports overloading of constructors, that means, we can have constructors with different sets of parameters. So, our class can be like this:

                   public class mySampleClass
{
    public mySampleClass()
    {
        // This is the no parameter constructor method.
        // First Constructor
    }

    public mySampleClass(int Age)
    {
        // This is the constructor with one parameter.
        // Second Constructor

    }

    public mySampleClass(int Age, string Name)
    {
        // This is the constructor with two parameters.
        // Third Constructor
    }

    // rest of the class members goes here.
}

Well, note here that call to the constructor now depends on the way you instantiate the object. For example:mySampleClass obj = new mySampleClass() 

At this time the code of no parameter constructor (First Constructor)will be executed mySampleClass obj = new mySampleClass(12)

At this time the code of one parameter constructor(Second Constructor) will be executed.
You can always make a call to one constructor from within another. Say, for example:

                   public class mySampleClass
{
    public mySampleClass(): this(10)
    {
        // This is the no parameter constructor method.
        // First Constructor
    }

    public mySampleClass(int Age)
    {
        // This is the constructor with one parameter.
        // Second Constructor
    }
}

Very first of all, let us see what is this syntax:

public mySampleClass(): this(10)

Here, this refers to same class, so when we say this(10), we actually mean execute the
public mySampleClass(int Age) method. The above way of calling the method is called initializer.
We can have at the most one initializer in this way in the method. Another thing, which we must know is the execution sequence i.e., which method will be executed when. Here, if I instantiate the object as

mySampleClass obj = new mySampleClass()

Then the code of public mySampleClass(int Age) will be executed before the code of
mySampleClass(). So, practically the definition of the method:

public mySampleClass(): this(10)
{
    // This is the no parameter constructor method.
    // First Constructor
}
is equivalent to:

public mySampleClass()
{
    mySampleClass(10)
    // This is the no parameter constructor method.
    // First Constructor
}
 We cannot make an explicit call to the constructors in C#, treating them as if any simple method, for example: statement mySampleClass(10) in the above code will not work. The only way you can call one constructor from another is through initializers.

Behavior of Constructors in Inheritance
Let us first create the inherited class.

                   public class myBaseClass
{
    public myBaseClass()
    {
        // Code for First Base class Constructor
    }

    public myBaseClass(int Age)
    {
        // Code for Second Base class Constructor
    }

    // Other class members goes here
}

public class myDerivedClass : myBaseClass
// Note that I am inheriting the class here.
{
    public myDerivedClass()
    {
        // Code for the First myDerivedClass Constructor.
    }

    public myDerivedClass(int Age):base(Age)
    {
        // Code for the Second myDerivedClass Constructor.
    }

    // Other class members goes here
}

Now, what will be the execution sequence here:

If I create the object of the derived class as:
myDerivedClass obj = new myDerivedClass()

Then the sequence of execution will be:
1.public myBaseClass() method.
2. and then public myDerivedClass() method

If I create an object of the derived class as::
                   myDerivedClass obj = new myDerivedClass(15)
         
Then the sequence of execution will be:
1.public myBaseClass(int Age) method
2.and then public myDerivedClass(int Age) method

Private constructors

Private constructors, the constructors with the “private” access modifier, are a bit special case. It is because we can neither create the object of the class, nor can we inherit the class with only private constructors. But yes, we can have the set of public constructors along with the private constructors in the class and the public constructors can access the private constructors from within the class through constructor chaining.

Say for example, my class is something like this :

public class myClass
{
    private MyClass()
    {
        Console.WriteLine("This is no parameter Constructor");
    }

    public MyClass(int var):this()
    {
        Console.WriteLine("This is one parameter Constructor");
    }   
    // Other class methods goes here
}

Then we can create the object of this class by the statement:

MyClass obj = new MyClass(10);
The above statement will work fine, but the statement

MyClass obj = new MyClass(); will raise an error
 Static Constructors
This is a new concept introduced in C#. By new here, I mean that it was not available for the C++ developers. This is a special constructor and gets called before the first object is created of the class. The time of execution cannot be determined, but it is definitely before the first object creation - could be at the time of loading the assembly.

The syntax of writing the static constructors is also damn simple. Here it is:

public class myClass
{
    static myClass()
    {
        // Initialization code goes here.
        // Can only access static members here.
    }
    // Other class methods goes here
}

Notes for Static Constructors:

1.There can be only one static constructor in the class.
2.The static constructor should be without parameters.
3.It can only access the static members of the class.
4.There should be no access modifier in static constructor definition.

The following points hold good for static constructors:

  • A Static constructor cannot be overloaded.
  • It should be without parameters and can only access static members.
  • It cannot have any access modifiers.
  • The static constructor for a class executes only once in an application domain.
  • Static constructors cannot be chained with other static or non-static constructors.

Now, one question raises here, can we have two constructors as:

public class myClass
{
    static myClass()
    {
        // Initialization code goes here.
        // Can only access static members here.
    }
    public myClass()
    {
        // Code for the First myDerivedClass Constructor.
    }

    // Other class methods goes here
}

This is perfectly valid, though doesn’t seem to be in accordance with overloading concepts. But why? Because the time of execution of the two methods are different. One is at the time of loading the assembly and one is at the time of object creation. 

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 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 and each shape has its own color. Each shape has also particular formulas to calculate its area and perimeter.

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:

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.

Abstract Classes and Class Members
Abstraction is "the process of identifying common patterns that have systematic variations;
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.
Classes can be declared as abstract. This is accomplished by putting the keyword abstract before the keyword class in the class definition. For example:
public abstract class A
{
    // Class members here.
}

An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.

Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method. For example:

public abstract class A
{
    public abstract void DoWork(int i);
}

Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods. When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method. For example:

public class D
{
    public virtual void DoWork(int i)
    {
        // Original implementation.
    }
}

public abstract class E : D
{
    public abstract override void DoWork(int i);
}

public class F : E
{
    public override void DoWork(int i)
    {
        // New implementation.
    }
}

To following code shows a sample implementation of an abstract class:
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();
}
}

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

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);
}
}
}

Abstract class Introduction
Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes that only represent base classes, and don’t want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract'.

An abstract class means that, no object of this class can be instantiated, but can make derivations of this.

An example of an abstract class declaration is:
abstract class absClass
{
}

An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.

An example of an abstract method:
abstract class absClass
{
  public abstract void abstractMethod();
}

Also, note that an abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract members. For example:

abstract class absClass
{
    public void NonAbstractMethod()
    {
        Console.WriteLine("NonAbstract Method");
    }
}

A sample program that explains abstract classes:

using System;

namespace abstractSample
{
      //Creating an Abstract Class
      abstract class absClass
      {
            //A Non abstract method
            public int AddTwoNumbers(int Num1, int Num2)
            {
                return Num1 + Num2;
            }

            //An abstract method, to be
            //overridden in derived class
            public abstract int MultiplyTwoNumbers(int Num1, int Num2);
      }

      //A Child Class of absClass
      class absDerived:absClass
      {
            [STAThread]
            static void Main(string[] args)
            {
               //You can create an
               //instance of the derived class

               absDerived calculate = new absDerived();
               int added = calculate.AddTwoNumbers(10,20);
               int multiplied = calculate.MultiplyTwoNumbers(10,20);
               Console.WriteLine("Added : {0},
                       Multiplied : {1}", added, multiplied);
            }

            //using override keyword,
            //implementing the abstract method
            //MultiplyTwoNumbers
            public override int MultiplyTwoNumbers(int Num1, int Num2)
            {
                return Num1 * Num2;
            }
      }
}
In the above sample, you can see that the abstract class absClass contains two methods AddTwoNumbers and MultiplyTwoNumbers. AddTwoNumbers is a non-abstract method which contains implementation and MultiplyTwoNumbers is an abstract method that does not contain implementation.

The class absDerived is derived from absClass and the MultiplyTwoNumbers is implemented on absDerived. Within the Main, an instance (calculate) of the absDerived is created, and calls AddTwoNumbers and MultiplyTwoNumbers. You can derive an abstract class from another abstract class. In that case, in the child class it is optional to make the implementation of the abstract methods of the parent class.
Example
//Abstract Class1
abstract class absClass1
{
    public abstract int AddTwoNumbers(int Num1, int Num2);
    public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}

//Abstract Class2
abstract class absClass2:absClass1
{
    //Implementing AddTwoNumbers
    public override int AddTwoNumbers(int Num1, int Num2)
    {
        return Num1+Num2;
    }
}

//Derived class from absClass2
class absDerived:absClass2
{
    //Implementing MultiplyTwoNumbers
    public override int MultiplyTwoNumbers(int Num1, int Num2)
    {
        return Num1*Num2;
    }
}

In the above example, absClass1 contains two abstract methods AddTwoNumbers and MultiplyTwoNumbers. The AddTwoNumbers is implemented in the derived class absClass2. The class absDerived is derived from absClass2 and the MultiplyTwoNumbers is implemented there.
Abstract properties

Following is an example of implementing abstract properties in a class.

//Abstract Class with abstract properties
abstract class absClass
{
    protected int myNumber;
    public abstract int numbers
    {
        get;
        set;
    }
}

class absDerived:absClass
{
    //Implementing abstract properties
    public override int numbers
    {
        get
        {
            return myNumber;
        }
        set
        {
            myNumber = value;
        }
    }
}

In the above example, there is a protected member declared in the abstract class. The get/set properties for the member variable myNumber is defined in the derived class absDerived.
Important rules applied to abstract classes

An abstract class cannot be a sealed class. I.e. the following declaration is incorrect.

//Incorrect
abstract sealed class absClass
{
}

Declaration of abstract methods are only allowed in abstract classes.
An abstract method cannot be private.

//Incorrect
private abstract int MultiplyTwoNumbers();

The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.

An abstract method cannot have the modifier virtual. Because an abstract method is implicitly virtual.

//Incorrect
public abstract virtual int MultiplyTwoNumbers();
An abstract member cannot be static.

//Incorrect
publpublic abstract static int MultiplyTwoNumbers();

Abstract class vs. Interface

An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.

An example of interface:
interface iSampleInterface
{
  //All methods are automaticall abstract
  int AddNumbers(int Num1, int Num2);
  int MultiplyNumbers(int Num1, int Num2);
}

Defining an abstract class with abstract members has the same effect to defining an interface.
The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.

A class can inherit one or more interfaces, but only one abstract class.
Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.

The selection of interface or abstract class depends on the need and design of your project. You can make an abstract class, interface or combination of both depending on your needs.

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.
Interfaces are by default public, no need to mention the public key word.

If suppose there are two interfaces

interface Interface1
{
          void CalculateArea();
          void CalculatePerimeter();
}
interface Interface2
{
          void CalculateArea1();
          void CalculatePerimeter1();
}

public class DerivedClass1 : Interface1,Interface2
{
          public void CalculateArea()
          {
                   System.Web.HttpContext.Current.Response.Write("hello");
          }
          public void CalculatePerimeter()
          {
                   System.Web.HttpContext.Current.Response.Write("hello1");
          }
          public void CalculateArea1()
          {
                   System.Web.HttpContext.Current.Response.Write("hello");
          }
          public void CalculatePerimeter1()
          {
                   System.Web.HttpContext.Current.Response.Write("hello1");
          }
}

Interface
interface is by default. no need to give the acess specifier. Interface is a template, it contains only the abstract method i.e. method definition. A derived class can implement any number of interfaces through this we are achieving multiple inheritance.

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.

An interface has the following properties:
·         An interface is similar to an abstract base class: any non-abstract type inheriting the interface must implement all its members.
·         An interface cannot be instantiated directly.
·         Interfaces can contain events, indexers, methods and properties.
·         Interfaces contain no implementation of methods.
·         Classes and structs can inherit from more than one interface.
·         An interface can itself inherit from multiple interfaces.

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.

Class A
{
public virtual int A();
}

Class B:A
{
public override int A()
{
//Implementation
}
}

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.
  
Sealed Class (In Visual Basic .NET, NotInheritable)
Sealed classes are used to restrict the inheritance feature of object-oriented programming. Once a class is defined as sealed class, this class cannot be inherited. If a class is derived from a sealed class, compiler throws an error.
In the following code, I create a sealed class SealedClass and use it from Class1. If you run this code, it will work fine. But if you try to derive a class from sealed class, you will get an error. 
using System;
class Class1
{
  static void Main(string[] args)
  {
 SealedClass sealedCls = new SealedClass();
 int total = sealedCls.Add(4, 5);
 Console.WriteLine("Total = " + total.ToString());
  }
}
// Sealed class
sealed class SealedClass
{
public int Add(int x, int y){
return x + y;
}
}

Sealed Classes and Class Members

Classes can be declared as sealed. This is accomplished by putting the keyword sealed before the keyword class in the class definition. For example:

public sealed class D
{
    // Class members here.
}

In C# a method can't be declared as sealed. However when we override a method in a derived class, we can declare the overrided method as sealed as shown below. By declaring it as sealed, we can avoid further overriding of this method.

A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes are primarily used to prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster.

A class member, method, field, property, or event, on a derived class that is overriding a virtual member of the base class can declare that member as sealed. This negates the virtual aspect of the member for any further derived class. This is accomplished by putting the sealed keyword before the override keyword in the class member declaration. For example:

public class D : C
{
    public sealed override void DoWork() { }
}
  
Why Sealed Classes?

We just saw how to create and use a sealed class. The main purpose of a sealed class to take away the inheritance feature from the user so they cannot derive a class from a sealed class. One of the best usage of sealed classes is when you have a class with static members. For example, the Pens and Brushes classes of the System.Drawing namespace. 
The Pens class represent the pens for standard colors. This class has only static members. For example, Pens. Blue represents a pen with blue color. Similarly, the Brushes class represents standard brushes. The Brushes.Blue represents a brush with blue color.
So when you're designing your application, you may keep in mind that you have sealed classes to seal user's boundaries.

Shadowing and Hiding

Shadowing :- This is a VB.Net Concept by which you can provide a new implementation for the base class member without overriding  the member. You can shadow a base class member in the derived class by using the keyword "Shadows". The method  signature, access level and return type of the shadowed member can be completely different than the base class member.

Hiding : - This is a C# Concept by which you can provide a new implementation for the base class member without overriding the  member. You can hide a base class member in the derived class by using the keyword "new". The method signature, access level and  return type of the hidden member has to be same as the base class member.

Upto now the code shown was for overriding a base class method with the child class method, But what will happen If you want to provide the base class behaviour instead, use the new directive, with or without virtual at the base class  Is this possible in C#? Yes, it is and that is the concept of shadowing in C# using a keyword "new' which is a modifier used instead of "override".

Check out in the code below
public class ClassA
 {
          public virtual void MethodA()
          {
                   Trace.WriteLine("ClassA Method");
          }
}
public class ClassB : ClassA
{
public new void MethodA()
{
Trace.WriteLine("SubClass ClassB Method");
}
}
public class TopLevel
{       
static void Main(string[] args)
{
TextWriter tw = Console.Out;
Trace.Listeners.Add(new TextWriterTraceListener(tw));

ClassA obj = new ClassB(); 
obj.MethodA(); // Outputs “Class A Method"

ClassB obj1 = new ClassB();                  
obj.MethodA(); // Outputs “SubClass ClassB Method”      
}
}