Object Oriented Programming Concepts

It is a methodology to write the program where we specify the code in form of classes and objects.

CLASS:-Class is a user defined data type. It is like a template. In c# variable are termed as instances of classes. Which are the actual objects?
EX:-
Class classname
{
  [variable declaration;]
  [Method declaration;]
}
Here Class is a keyword and class name is valid c# identifier. Everything inside the square brackets is optional.It is also valid class definition.

EX:- 
Class Empty
{

}

OBJECT:- Object is run time entity which has different attribute to identify it uniquely.

EX:-
Here this is an example of creating an object of type Rectangle.

Rectangle rect1=new rectangle();
Rectangle rect1=new rectangle();

Here variable 'rect1' & rect2 is object of the rectangle class.
The Method Rectangle() is the default constructor of the class. We can create any number of objects of Rectangle class.

Basic Principle of oops:- 
There are main three core principles of  any object oriented languages.

·                     ENCAPSULATION: - Encapsulation provides the ability to hide the internal details of an object from its users. The concept of encapsulation is also known as data hiding or information hiding. In c#, Encapsulation is implemented using the access modifier keywords.
1.                  Public
2.                  Private
3.                  protected
4.                  Internal
5.                  Protected Internal

·                     POLYMORPHISM: - It is also concept of oops. It is ability to take more than one form. An operation may exhibit different behavior in different situations.                                                          
 Ex: - An addition operation involving two numeric values will produce sum and the same addition operation will produce a string. If we pass parameter numeric value then method return sum (numeric value) and if we pass parameter String then same method is return string value .this called Polymorphism.

·                     INHERITANCE: - One class can include the feature of another class by using the concept of inheritance. In c# a class can be inherit only from one class at a time. Whenever we create class that automatic inherit from System.Object class, till the time the class is not inherited from any other class.

Constructor
          A constructor is a special type of method that is invoked when you create a new instance of a class.
          Constructor has the same name as that of the class.
          Constructor is used to initialize member variables.
If there are no constructors defined for a class, the compiler creates a default constructor.

Types of Constructors:
       Instance Constructor
       Static Constructor

Instance Constructor
An Instance Constructor is called whenever an instance of a class is created:-

using System;
namespace CSharp
{
    class Program
    {
        static int num1, num2, total;
        //Constructor
        Program()
        {
            num1 = 10;
            num2 = 20;
        }
        public void AddNum()
        {
            total = num1 + num2;
        }
        public void DisplayNum()
        {
            Console.WriteLine("The total is {0}",total);
        }
        static void Main(string[] args)
        {
            Program Obj = new Program();
            Obj.AddNum();
            Obj.DisplayNum();
        }
    }
}




The total is 30

Static Constructors

          Static Constructors are used to initialize the static variables of a class.
          They have implicit private access.
          The constructor will be invoked only one during the execution of a program.

class Program
    {
        static int num1;
        int num2;
        //static Constructor
        static Program()
        {
            num1 = 10; //Ok.Since Num1 is a staic variable.
            num1 = 20; //Error.Since Num2 is a non-static variable.
        }
    }

Constructors with Parameters
using System;
namespace CSharp
{
    class Program
    {
        static int num1, num2, total;
        //Constructor
        Program(int No1, int No2)
        {
            num1 = No1;
            num2 = No2;
        }
        public void AddNum()
        {
            total = num1 + num2;
        }
        public void DisplayNum()
        {
            Console.WriteLine("The total is {0}",total);
        }
        static void Main(string[] args)
        {
            int var1,var2;
            Console.WriteLine("Enter value 1:");
            var1=Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter value 2:");
            var2=Convert.ToInt32(Console.ReadLine());
            Program Obj = new Program(var1,var2);
            Obj.AddNum();
            Obj.DisplayNum();
            Console.ReadLine();
        }
    }
}


 

Enter value 1:
10
Enter value 2:
20
The total is 30

Destructors

          Destructors are special methods that are used to release the instance of a class from memory.
          A class can have only one destructor.
          The programmer has no control on when to call the destructor.
          Destructor has the same name as its class but is prefixed with a ~(tilde) symbol.
          Even if you don’t call the destructor, garbage collector releases memory.

class Program
    {
        //Constructor
        Program()
        {
            Console.WriteLine("Constructor Invoked");
        }
        //Destructor
        ~ Program()
        {
            Console.WriteLine("Destructor Invoked");
        }


        static void Main(string[] args)
        {
            Console.WriteLine("Main Begins");
            Program Ojb = new Program();
            {
                Console.WriteLine("Inner Block Begins");
                Program Ojb2 = new Program();
                Console.WriteLine("Inner Block Ends");
            }
            Console.WriteLine("Main Ends");
        }
    }


 

Main Begins
 Inner Block Begins
 Constructor Invoked
 Inner Block Ends
 Main Ends
 Destructor Invoked

Polymorphism

          Greek words “poly” and “morphs” mean “many” and “forms” respectively.
          Often expressed as “One Interface, Multiple Functions”.
          Polymorphism is the ability that helps in executing different operations to the same message.

Polymorphism provides following features: 

·         It allows you to invoke methods of derived class through base class reference during runtime.
·         It has the ability for classes to provide different implementations of methods that are called through the same name. 

Polymorphism is of two types:
 
1.       Compile time polymorphism/Overloading
2.       Runtime polymorphism/Overriding


Compile Time Polymorphism

Compile time polymorphism is method and operators overloading. It is also called early binding.

In method overloading method performs the different task at the different input parameters.

Runtime Time Polymorphism

Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding.

Types of Compile Time Polymorphism:

        Method Overloading: This approach allows using the same name for two or more function; each redefinition of a function must use different types of parameters, sequence of parameters, or a number of parameters.
        Operator Overloading: This approach allows user-defined types such as structures and classes to use overloading operators for easy manipulation of their objects.

Method overloading
class Program
    {
        public int Max(int num1, int num2)
        {
            if (num1 > num2)
                return num1;
            else
                return num2;
        }
        public float Max(float num1, float num2)
        {
            if (num1 > num2)
                return num1;
            else
                return num2;
        }
        static void Main(string[] args)
        {
            Program obj = new Program();
            Console.WriteLine(“Max Value is : {0}”obj.Max(19,20));
        }
    }


Max Value is : 20

Constructor Overloading

class Program
    {
        float max;
        Program(int num1, int num2)
        {
            if (num1 > num2)
                max= num1;
            else
                max= num2;
        }
        Program(float num1, float num2)
        {
            if (num1 > num2)
                max = num1;
            else
                max = num2;
        }
        static void Main(string[] args)
        {
            Program obj = new Program(10,20);
            Console.WriteLine("Max is :"+obj.max);
        }
    }

 

Max Value is : 20



Operator Overloading
class Program
    {
        public int num1, num2;
        public Program(int num1, int num2)
        {
            this.num1 = num1;
            this.num2 = num2;
        }
        public static Program operator - (Program p1)
        {
            p1.num1 = -p1.num1;
            p1.num2 = -p1.num2;
            return p1;
        }
        public void Print()
        {
            Console.WriteLine("Number 1= " + num1);
            Console.WriteLine("Number 2= " + num2);
        }
        static void Main(string[] args)
 {
            Program Obj = new Program(15,25);
            //using overloading operator
            Obj = -Obj;
            Obj.Print();
        }
    }

Inheritance

Classes can be defined as deriving from a base class. A derived class inherits all of the ancestors protected and public methods and data members.

The Class can acquires the properties and Methods of another class is called Inheritance
Example :
Shape  - Base Class or Parent Class or Super Class
Square,Triangle, Circle - Derived Class or Sub class or
Child Class
Derived class uses the Properties of
Base Class
(Eg. Square uses the Properties
 and Methods of Shape Class)



Inheritance

public class Shape             //  BASE CLASS
{                     
            public double area;
            public Shape()
            {
            area=0.0;
             }
            public void display(string ShapeName,double a)
            {
                        Console.WriteLine("The area of          “ +ShapeName +" is "+ a);
            }
}
                                               
  
Shape (Base Class)
public class Square:Shape//DERIVED CLASS

{
            int Side;
public Square(int a)
{
            Side=a;
}
            public void CalculatePerimeter()
            {
            area=4 * Side * Side;
            }
}

public class Circle:Shape //DERIVED CLASS
{
int r;
public Circle(int radius)
{
            r=radius;
}
public void CalculateArea()
{
            area=3.14 * r * r;           
}
}

                                                                                                             
Circle Class inherits Shape’s “Display()” Method
 class MainClass
{
            [STAThread]
            static void Main( )
            {
            Circle objCircle=new Circle(5);
            objCircle.CalculateArea();  //Derived Class Method
            objCircle.display("Circle",objCircle.area); // Base Class Method
            Square objSquare=new Square(5);                   objSquare.CalculatePerimeter(); //Derived Class Method
            objSquare.display("Square",objSquare.area); // Base Class Method
            }
}
  


Abstract Classes
          Abstract classes are used to provide partial class implementation of an interface. One can complete implementation by using the derived classes.
          Abstract classes contain abstract methods, which can be implemented by the derived class.
          Polymorphism can be implemented by using abstract classes and virtual functions.
          Abstract classes cannot create an instance of an abstract class.
          One cannot declare an abstract method outside an abstract class.
          An abstract class cannot be declared sealed.
          Abstract methods have to override by the derived class..

An abstract class with a non-abstract method.

The keyword abstract can be used with both classes and methods in C# to declare them as abstract.

          The classes, which we can't initialize, are known as abstract classes. They provide only partial implementations. But another class can inherit from an abstract class and can create their instances.

              For example, an abstract class with a non-abstract method.

Example
using System;
abstract class MyAbs
{
public void NonAbMethod()
{
Console.WriteLine("Non-Abstract Method");
}
}
class MyClass : MyAbs
{
}
class MyClient
{
public static void Main()
{
//MyAbs mb = new MyAbs();//not possible to create an instance
MyClass mc = new MyClass();
mc.NonAbMethod(); // Displays 'Non-Abstract Method'
}
}

     Output
Non-Abstract Method
    

Partial implementation of an abstract class.

By declaring the derived class also abstract, we can avoid the implementation of all or certain abstract methods. This is what is known as partial implementation of an abstract class.

Example
using System;
abstract class MyAbs
{
public abstract void AbMethod1();
public abstract void AbMethod2();
}
//not necessary to implement all abstract methods
//partial implementation is possible
abstract class MyClass1 : MyAbs
{
public override void AbMethod1()
{
Console.WriteLine("Abstarct method #1");
}
}
class MyClass : MyClass1
{
public override void AbMethod2()
{
Console.WriteLine("Abstarct method #2");
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.AbMethod1();
mc.AbMethod2();
}
}
     Output
Non-Abstract Method
Abstract method

Virtual Functions

          These functions are defined in a class which we want to allow to be implemented by the inherited classes.
         The virtual function could be implemented by the inherited classes in their own way and the call to the method is decided at runtime.

public class Dimensions
    {
        public const double PI = Math.PI;
        protected double x, y;
        public Dimensions()
        {
        }
        public Dimensions(double x, double y)
        {
            this.x = x;
            this.y = y;
        }
        public virtual double Area()
        {
            return x * y;
        }
    }
    public class Circle : Dimensions
    {
        public Circle(double r) : base(r, 0)
        {
        }
        public override double Area()
        {
            return PI * x * x;
        }
}
_______________________________________________________________
    class Sphere : Dimensions
    {
        public Sphere(double r) : base(r, 0)
        {
        }
        public override double Area()
        {
            return 4 * PI * x * x;
        }
    }
    class TestClass
    {
        static void Main()
        {
            double r = 3.0, h = 5.0;
            Dimensions c = new Circle(r);
            Dimensions s = new Sphere(r);
            Console.WriteLine("Area of Circle = {0:F2}", c.Area());
            Console.WriteLine("Area of Sphere = {0:F2}", s.Area());
        }
    }
_______________________________________________________________

Sealed Classes

          Keyword “sealed” is used to restrict the users from inheriting the class by sealing the class.
          No class can be derived from a sealed class.
          A method can never be declared as sealed.
          An overriden method can also be declared sealed.

Example
using System;
 sealed class MyClass
{
public int x;
public int y;
}
 class MainClass
{
public static void Main()
{
MyClass mC = new MyClass();
 mC.x = 110; mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
}
}
In the preceding example, if you attempt to inherit from the sealed class by using a statement like this:
     class MyDerivedC: MyClass {} // Error
          You will get the error message:


          'MyDerivedC' cannot inherit from sealed class 'MyBaseC'.
          In C# a method can't be declared as sealed. However when we override a method in a derived class,

METHOD OVERRIDING IN SEALED

                     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 .
                      By declaring it as sealed, we can avoid further overriding of this method.

EXAMPLE
using System;
 class MyClass1
{
 public int x;
 public int y;
 public virtual void Method() {
 Console.WriteLine("virtual method"); } }
 class MyClass : MyClass1
 {
   public override sealed void Method()
 {
     Console.WriteLine("sealed method"); }
}
 class MainClass
{
  public static void Main()

 {
   MyClass1 mC = new MyClass();
 mC.x = 110; mC.y = 150;
 Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y); mC.Method();
} }
OUTPUT
X=110;Y=150
Sealed method

Interfaces

          An interface defines the syntactical contract that all the derived classes should follow.
          An Interface also define properties, methods, events which are known as the members of the interface.
          Interface contains only the declaration of members.
          An Interface can inherit members from an existing interface.
          Interfaces support multiple inheritance.

Defining Interface:
An interface can contain one or more methods,properties,indexers and events but none of them are implemented in interface itself. 

Syntax:


Here,interface is the keyword and interface name  is a valid C# identifier.

Ex:
interface IMyInterface
{
    void MethodToImplement();
}

Interface Inheritance:

using System;

interface IParentInterface
{
    void ParentInterfaceMethod();
}

interface IMyInterface : IParentInterface
{
    void MethodToImplement();
}

class InterfaceImplementer : IMyInterface
{
    static void Main()
    {
        InterfaceImplementer iImp = new InterfaceImplementer();
        iImp.MethodToImplement();
        iImp.ParentInterfaceMethod();
    }

    public void MethodToImplement()
    {
        Console.WriteLine("MethodToImplement() called.");
    }

    public void ParentInterfaceMethod()
    {
        Console.WriteLine("ParentInterfaceMethod() called.");
    }
}
Output:
MethodToImplement() called
ParentInterfaceMethod() called
          

              ____________________________________________________________________
Reach us At: - 0120-4029000; 0120-4029024; 0120-4029025, 0120-4029027; 0120-4029029
Mbl: 9953584548
Write us at: - Smruti@apextgi.com and pratap@apextgi.com

No comments:

Post a Comment