Showing posts with label C# basics. Show all posts
Showing posts with label C# basics. Show all posts

Monday, 18 March 2013

Thread locking or Thread Synchronization

In the below Program all the three threads that are created in program are calling the same method for execution at the same time. So in this case if we execute the program and watch the output we will result that are unexpected.
The problem behind the execution is write now the method is a asynchronous method which can be called by multiple threads at a time.
To overcome the problem with asynchronous we need to first make the method as a synchronous method by adopting the process of thread locking or thread synchronous which can be done putting the methods under the special 'lock' block.
Uncomment the commented section and watch the output.

using System;
using System.Threading;


namespace CSharpConsole
{
    class ThreadDemo4
    {
        Thread t1, t2, t3;
        public ThreadDemo4()
        {
            t1 = new Thread(Display);
            t2 = new Thread(Display);
            t3 = new Thread(Display);
            t1.Start(); t2.Start(); t3.Start();

        }
        // Asynchronous Method
        public void Display()
        {
            Console.WriteLine("[CSharp is  ");
            Thread.Sleep(5000);
            Console.WriteLine("Object Oriented]");

        }
        /* Synchronous Method
        public void Display()
        {
            lock (this)
            {
                Console.Write("[ CSharp is ");
                Thread.Sleep(5000);
                Console.WriteLine("Object Oriented ]");
            }
        }*/
 
            static void Main()
        {
            ThreadDemo4 obj = new ThreadDemo4();
            obj.t1.Join(); obj.t2.Join(); obj.t3.Join();
            Console.ReadLine();
        }

    }
    
}

Friday, 15 March 2013

Multithreading in C#

  • It is an approach which allows a single program to perform multiple actions simultaneously.  Earlier we had an approach of multitasking where in this case we can execute multiple programs at a given point of time. Operating system is responsible for multitasking where all operating systems are not multitasking Operating system. Windows. MAC, Linux are multitasking Operating systems whereas DOS is a single tasking Operating system. If we want to develop a multithreaded application first the support should be available under the programming language whereas the language will internally take the support of Operating system again. C# language supports multitasking.
  • A thread is a unit of execution which is responsible in executing the program known as main thread. So by default every language is multithreaded.
  • In a single threaded program the execution takes place by performing its actions one by one ie suppose it has started calling a method until and unless that method execution is completed it cannot go to the other methods for execution. So if at all a method is taking more time to execute than the expected until that time all the other methods has to wait.
  • to overcome the problems with single threaded applications, multithreading was designed wherein multithreading we can use a separate thread for calling each method.

  • Multithreading has been designed for maximum utilization of CPU resources. So multithreaded applications execute adopting 2 principals.
  1. Time Sharing: Here Operating system allocates time period for each thread for executing the methods and transfers the control to another thread once the time is elapsed giving equal importance for all the threads to execute.
  2. Maximum utilization of resources: This comes into picture only if the first principal violates ie if a thread could not execute in its given time period for some reason without wasting at that thread Operating system transfers the control to the other threads in execution.

How to define an exception class ?

If we want to define an exception class we  need to adopt the following process:
  1. Define a class by inheriting from predefined class exception so that a new class is also an exception.
  2. Overwrite the message properly and provide the error message that has to be given when the exception occurred.
Add a new class DivideByOddNoException and  write the following code:

 
using System;

namespace CSharpConsole
{
    class DivideByOddNoException: Exception 
    {
        public override string Message
        {
            get
            {
                return "Attempted to divide by odd number ";
            }
        }
   }
}
 Add a new class ThrowDemo.cs and write the following code:

using System;

namespace CSharpConsole
{
    class ThrowDemo
    {
        static void Main()
        {
            int x, y, z;
            Console.Write("Enter x value ");
            x = int.Parse(Console.ReadLine());
            Console.Write("Enter y value ");
            y = int.Parse(Console.ReadLine());
            if (y % 2 > 0)
            {
                throw new DivideByOddNoException();
                //throw new ApplicationException("Divisor should not be an odd number ");
            }
            z = x / y;
            Console.WriteLine(z);
            Console.WriteLine("End of program ");
        }
    }
}

Wednesday, 13 March 2013

Exceptions in C#

When we write a program there are chances of coming across 2 different types of errors
  • Compile-time Errors
  • Run-time Errors.
An error which comes into picture at the time of program compilation is a compile-time error which may occur due to syntax mistakes. An error which occurs in the middle of the programs execution is known as a run-time error and these errors occur due to various reasons like wrong implementation of logic, wrong inputs supplied to a program, missing of required resources etc. 
A compile-time error is not dangerous because it occurs at the time of compilation whereas run-time errors are dangerous because they occur in the program when the execution is going on and if at all a run-time error occurs in a program, the program terminates abnormally on the same line where the error gets occured without executing the rest of the code.

Note:  Whenever an error situation occurs in a program the exception handler comes into picture to identify the type of error and then creates an object of an exception class associated with that error and throws that object and that object will first terminate the program abnormally and then displays an error message associated with an exception object.

Exception Handling

Whenever a run- time error occurs under the program abnormal termination is occuring so we will be facing so many problems in the application. To overcome the problems we are provided with a mechanism known as Exception Handling.

Exception Handling is a process of stopping the abnormal termination of the program whenever the exceptions are terminating the program in case of run time error. If we can stop the abnormal termination of a program we will be getting following advantages :
  • We can make the statement which are not associated with the error.
  • We can display a user friendly error message to the end user so that he can resolve the error, got occurred provided if it is in his hands.
  • We can also perform some corrective actions to come out of a problems that may occur due to error.
To handle an exception we need to enclose our code under some special blocks known as try catch block which should be used as following:

try
{
-statements which requires execution when the run time error occurs.
-statements which does not require execution only when the run time error occurs.
}
catch
{
-statements which requires execution only when the run time error occurs.
}
[--< multiple catch blocks if required >--]

Add a class Exception demo.cs and write the following code:


using System;

namespace CSharpConsole
{
    class ExceptionDemo
    {
        static void Main()
        {
            int x, y, z;
            try
            {
                Console.WriteLine("Enter x value: ");
                x = int.Parse(Console.ReadLine());

                Console.WriteLine("Enter y value: ");
                y = int.Parse(Console.ReadLine());

                z = x / y;
                Console.WriteLine(z);
            }
            catch (DivideByZeroException ex1) //ex1 is a variable of class          DivideByZeroException
            {
                Console.WriteLine("Divisor must not be zero");
            }
            catch (FormatException ex2) //ex2 is a variable of class FormatException
            {
                Console.WriteLine("Input must be numeric");
            }

            catch (Exception ex3)
            {
                Console.WriteLine(ex3.Message);//message is a read only property
            }
            {
                Console.WriteLine("End of the program");
                Console.ReadLine();
            }
         }
    }
}

Tuesday, 12 March 2013

Types of Delegates

Delegates are of two types:
  • Unicast Delegate
  • Multicast Delegate
If a delegate is used for calling a single method we call it as a unicast delegate whereas if a delegate is use for calling multiple methods its a multicast delegate.
In case of the methods delegate, a single delegate call will execute all the methods that are bound with the delegate.
using System;

namespace CSharpConsole
{
    public  delegate void MathDel(int x, int y);
    class DelMulti
    {
        public void Add(int x, int y)
        {
            Console.WriteLine("Add:  " + (x + y));
        }
        public void Sub(int x, int y)
        {
            Console.WriteLine("Sub:  " + (x - y));
        }
        public void Mul(int x, int y)
        {
            Console.WriteLine("mul:  " + (x * y));
        }
        public void Div(int x, int y)
        {
            Console.WriteLine("Div:  " + (x / y));
        }
        static void Main()
        {
            DelMulti obj = new DelMulti();
            MathDel md=new MathDel (obj.Add );
            md+=obj.Sub ;md +=obj.Mul ;md +=obj.Div ;
            md(100,25);
            Console .WriteLine ();
            md(600,30);
            Console .WriteLine ();
            md -=obj.Mul ;
            md(450,50);
            Console .ReadLine ();
            
        }

    }
}
 

 

Delegates in C#

It is also an user defined type which is used for invoking or calling the methods of a class.

A method that is defined under a class can be called in 2 different ways
  • With the help of object of a class if it is non static or name of a class if it is static.
  • By using the delegate also we can call  the method of a class even if it is static or non static.
Note: Calling the method in the 1st process is different than calling the method in the 2nd process.

Calling a method using a Delegate

       If we want to call a method using a delegate we need to adopt the following process
  • Defining a delegate:   
[<modifiers>] delegate <void/type> <Name> ([<Parameter Definition's>])

The definition of a delegate is similar to a method definition where a method will have body whereas a delegate will not have any body where we use these delegates for calling these methods.

Note: While defining a delegate make sure the I/O parameters of Delegates are same as the I/O parameters of the method we want to call with the help of a delegate.
  • As the delegate is a type, after defining a delegate to consume it we need to create an object of it and while creating the object, the method we want to call using the delegate should be passed as a parameter to the delegates constructor.
  • Now call the delegate by passing the required parameter value so that the method gets executed internally.

Delegate Example


using System;
namespace CSharpConsole
{
    class DelDemo
    {
        public void Add(int x, int y)
        {
            Console.WriteLine(x + y);
        }
        public static string SayHello(string name)
        {
            return "Hello " + name;
        }
        public delegate void AddDel(int a, int b);
        public delegate string SayDel(string name);

        static void Main()
        {
            DelDemo obj = new DelDemo();
            AddDel ad = new AddDel(obj.Add);
            SayDel  sd = new SayDel (DelDemo.SayHello);
            ad(100, 50); ad(234, 434); ad(672, 157);
            Console.WriteLine(sd("AAA"));
            Console.WriteLine(sd("BBB"));
            Console.WriteLine(sd("CCC"));
            Console.ReadLine();
                   
        }
    }
}

Monday, 11 March 2013

Indexers in Csharp

These are also use for providing access to the values of the class outside of the class outside of the class like a property but provides access to a value with the specific name but indexers provides access to the value with the object of a class using index positions just like an array.
We define indexers in a class as following:

 Syntax:
[<modifiers>]<type> this [int index or srting name]
{
[get{<statements>}]
[set{<statements>}] 
}

Indexers are defined very much similar to properties but an indexer doesn't have any name. In the place of name we use the 'this' keyword which means we are definning an indexer object of that class starts providing access to the values that are present inside the class, either with the help  of index or name.

Add a class Employee.cs and write the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpConsole
{
    class Employee
    {
        int _Empno;
        string _Ename, _Job;
        double _Salary;
        public Employee(int Empno)
        {
            this._Empno = Empno;
            this._Ename = "Leena";
            this._Job = "Developer";
            this._Salary = 5000;
        }
        public object this[int index] // accessing by 'index' 
        {  
            //read/wrtie properties with conditions
            get
            {
                if (index == 0)
                    return _Empno;
                else if (index == 1)
                    return _Ename;
                else if (index == 2)
                    return _Job;
                else if (_Salary == 3)
                    return _Salary;
                return null;
            }
            //read/write properties with conditions
            set
            {
                if (index == 1)
                    _Ename = value.ToString();
                else if (index == 2)
                    _Job = value.ToString();
                else if(index==3)
                    _Salary =(Convert.ToDouble(value));
            }
        }
        public object this[string name]   //accessing by'name'
        {
            get
            {
                if (name == "Empno")
                    return _Empno;
                else if (name == "Ename")
                    return _Ename;
                else if (name == "Job")
                    return _Job;
                else if (name == "Salary")
                    return _Salary;
                return null;
            }
            set
            {
                if (name == "Ename")
                    _Ename = value.ToString();
                else if (name == "Job")
                    _Job = value.ToString();
                else if (name == "Salary")
                    _Salary = Convert.ToDouble(value);

            }
        }
    }
}
Add another class TestEmployee.cs and write the following code:
using System;

namespace CSharpConsole
{
    class TestEmployee
    {
        static void Main()
        {
            Employee emp = new Employee(1001);
            Console.WriteLine(emp[0]);
            Console .WriteLine (emp [1]);
            Console.WriteLine(emp[2]);
            Console.WriteLine(emp[3]);
            
            // Assigning a new value
            emp[1] = "Cheryl";
            emp["Ename"] = "BA";
            emp[3] = 8000;

            Console.WriteLine(emp["Empno"]);
            Console.WriteLine(emp["Ename"]);
            Console.WriteLine(emp["Job"]);
            Console.WriteLine(emp["Salary"]);
            Console.ReadLine();
        }
    }
}

Thursday, 7 March 2013

Properties

There are also members of a class using which we can provide access to the value of a class outside of the class.
If at all a class is associated with any values and if we want those values to be accessible outside of the class we can provide access to those values in two different ways.
  • By storing value under a public variable we can provide access to that value outside the class but in this case the public variable gives get value or set the value.
       public class Test
       {
       public int x=100;
       }
       Test obj=new Test()
       int a=obj x
       obj.x=100
  • By storing the value under a private value also of a class by defining a property on that variable given in three different ways
  1. Both get and set access(Read/write/property)
  2. Only get access(Read only property)
  3. Only set access(write only property)
Syntax to define a property:

      [<modifiers>]<type>[Names]
      {
      [get{statements}]  // Get accessor
      [set{statements}]  // Set accessor
      }


Wednesday, 6 March 2013

Methods of a 'class' in CSharp

A class is a collection of members, where members of class can be off various kinds like :
  • Fields
  • Members
  • Constructors
  • Destructors
  • Properties
  • Indexes
  • Events
  • Delegates
  • Enum
Destructor: This is also a special method present under a child class same like a constructor but constructor method gets called when object of class is created and destructor is called whenobject of class is destroyed.
   Both constructor and destructor method will exactly have the same name i.e the name of the class which they have. To differentiate between this two we use 'tidle' operation before the destructor method.

class Test
 {
    Test() 
     {
        //Constructors
     } 
   ~Test()
    {
      //Destructors
    }
}
  • Destructor methods cannot be applied with any modifirs or parameters.
  • Garbage Collector is responsible for destroying the object of class and when the object of class is being destroyed, destructor methods gets called and moreover Garbage Collector can destroy the object of class in any of the following three classes.
  1. In the end of a program's execution each and every object i.e associated with the program is automatically destroyed.
  2. Sometime in the middle of a programs execution implicit calling of Garbage Collector takes place provided the memory is full that it identifies finds unused object and destroys them.



Tuesday, 5 March 2013

Access Modifiers

Members that are defined in type by any scope on specific are always accessible within the type. Restrictions comes into picture only when we try to access them outside of the type. Members declared as private under a class or structure cant be access outside of the type in which they are defined and moreover there default scope is private only.

Types cant be declare as private so private can be use only on members. One point to keep in mind is that Interface cant contain any members and default scope for interface members is public.
  • Protected: Members declared as protected under a class be accessed only within the class or in a child class.Non child classes cant consume them. Types cant be declared as protected also, so this can only be used on members.
  • Internal: Members and types that are declared as internal can be consumed only within the project bot both from child or non child. The default scope for any type in C# is internal only.
  • Protected Internal: Members declared as protected will have dual scope i.e within the project they behave as internal providing access to anywhere in project outside the classes they will change to protected and still provide access to their child classes. Types cannot be declared as protected internal also. So this can also be used only on members.
  • Public: A type or member of a type if declared as public is global in scope which can be accessed from anywhere.

Thursday, 28 February 2013

Need of Abstract classes and Abstract Methods

The concept of abstract classes is an extension to the concept of inheritance. In inheritance the parent classes can be defined with attributes that are commonly required under multiple child classes providing reusability.

FIGURE
  • Rectangle
  • Circle
  • Triangle
  • Cone
In the above case when we want to define different entities representing various figures like Rectangle, Traingle, Circle, Cone etc in such cases first we identify the attributes that are commonly required and put them under a parent class.
The class Figure as it is the parent provides the attributes commonly required to all figures given reusability. Along with this we can also define any abstract in the parent class figure so that the child classes will implement the abstract members which is a restriction for the child classes and cannot escape from it.
   

Interfaces

  • This is also a user defined type same as a class but can contain only abstract members in it.
  • The abstract members of an Interface will be implemented by a child class of  the Interface so here also the Interface is imposing restrictions on the child class.
  • A child can be inherited either from another class or an Interface also. When a class is inheriting from another class it can inherit only from one class (Single Inheritance). When class is inheriting from an Interface it can be inherited from any number of interfaces (Multiple Inheritance).
  •  Inheritance is divided into two categories
  1.   Implementation Inheritance
  2.   Interface Inheritance
  • If a class is inheriting from another class we call it as implementation Inheritance and this provides reusibility because child classes can consume their parent class members.
  • If a class is inheriting from an Interface we call it as Interface Inheritance but Interface Inheritance does not provide any reusibility because here the child c lass is only implementing the methods of its parent Interface.
Syntax:
[<modifiers>]  Interface <Name>    
{
 Abstract class declaration
}   

Rules while working with Interfaces
  • We can not declare variables under an interface.
  • Default scope for a member of an Interface is public where as it is private in case of class.
  • Every member of an Interface is by default abstract so we don't require to declare explicitly.
  • An Interface can inherit from another Interface if required.
Add an Interface item template under the project by choosing Interface from the add new item window and name it interface1.cs

interface Interface1
    {
        void add(int x, int y);
        void sub(int x, int y);
    }

Add another interface interface2.cs and write the following code

interface Interface2
    {
        void mul(int x, int y);
        void div(int x, int y);
    }

Now to implement the members of both these interfaces add a class interclass.cs and write the following code
       
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApps
{
    class interclass: Interface1,Interface2
    {
        public void add(int x, int y)
        {
            Console.WriteLine(x + y);
        }
        public void sub(int x, int y)
        {
            Console.WriteLine(x - y);
        }
        public void mul(int x, int y)
        {
            Console.WriteLine(x * y);
        }
        public void div(int x, int y)
        {
            Console.WriteLine(x / y);
        }
        static void Main()
        {
            interclass c = new interclass();
            c.add(100,45);
            c.sub(89,26);
            c.mul(12,34);
            c.div(456,23);
            Console.ReadLine();
        }
    }
}

Wednesday, 27 February 2013

Abstract Methods and Abstract Classes

A method without any method body is known as a Abstract method. It will have only the defination for the method the method and to declare any method as abstract we need to use abstract modifier on the method.    
   A class under which we define abstract members is  known as a abstract class and it also has to be defined using abstract modifier.

 abstract modifier
{
   public abstract void Add(int x,int y);
}

The concept of abstract method is near similar to the concept of method overriding were in case of Method Overriding if any members of parent class are declared as virtual those methods can be re- implemented under the child class using the override modifier.

Add a classAbsParent.cs and write the following code:
using System;

namespace CSharpConsole
{
    abstract class AbsParent
    {
        public void Add(int x, int y)
        {
            Console.WriteLine(x + y);
        }
        public void Sub(int x, int y)
        {
            Console.WriteLine(x -y );
        }  

        public abstract void mul(int x, int y);
        public abstract void div(int x,int y);
        
    }
 }
//Add another class AbsChild.cs and write the following code:
using System;
namespace CSharpConsole
{
    class AbsChild: AbsParent
    {
        public override void  mul(int x, int y)
      {
       Console.WriteLine(x*y );
      }

        public override void  div(int x, int y)
      {
       Console .WriteLine (x/y );
      }
        
      static void Main()
        {
            AbsChild c = new AbsChild();
            c.Add(20, 12);
            c.Sub(15, 5);
            c.mul (5, 5);
            c.div (10, 5);
            Console.ReadLine();
      }
    }
}

Monday, 25 February 2013

Operator Overloading

   It is an approach of defining multiple behaviors to an operator just like we can define multiple behaviors to a method in method overloading.
   In method overloading a method will have different behaviors that are defined basing on the parameter types of that method. In the same way in operator overloading, a operator will have different behaviors based on the operands between which we use the operators.
   For example '+' is an overloaded operator which works as additional operator when used between two numeric operands and works as a concatenation operator when used with the string operands or string-numeric operands.
numeric+numeric=addition
string+string=concatenation
string+numeric=concatenation
   Same as we discussed about we can also add new behavior to  existing operators of the language by defining an operator method on that operator as following:
[<modifiers>] static <types> operator <opt> (<operand types>)
    A operator method must b defined as static only. Type refers to the data-type of the value what it returns when the operator is used between two operands. Operator is a keyword which tells we are defining an operator method. <opt> refers to the type of operands between which we want to use the operator.

Example of Operator Overloading


// Add a new class Matrix.cs
using System;
namespace CSharpConsole
{
    class Matrix
    {

        //declaring variables for a 2*2 matrix
        int a, b, c, d;
        public Matrix(int a, int b, int c, int d)
        {
            //initializing the matrix varaibles
            this.a=a ; this.b=b ;
            this.c=c ; this.d=d ;
        }

        // overloading the + operator so that it can be used for adding values of 2 matrix
        public static Matrix operator + (Matrix m1, Matrix m2)
        {
            Matrix obj = new Matrix(m1.a + m2.a, m1.b + m2.b, m1.c + m2.c, m1.d + m2.d);
            return obj;
        }

        // overloading the - operator so that it can be used for substracting values of 2 matrix
        public static Matrix operator -(Matrix m1, Matrix m2)
        {
            Matrix obj = new Matrix(m1.a - m2.a, m1.b - m2.b, m1.c - m2.c, m1.d - m2.d);
            return obj;
        }

        //overriding the ToString method inherited from object class for returning the values associated with matrix object
        public override string ToString()
        {
            return string.Format("[a:{0};b:{1};c:{2}:d:{3}]", a,b,c,d );
        }
    }
}
// Add another class TestMatrix to test the above code.

using System;
namespace CSharpConsole
{
    class TestMatrix
    {
        static void Main()
        {
            Matrix m1 = new Matrix(5, 6, 7, 8);
            Matrix m2 = new Matrix(1, 2, 3, 4);
            Matrix m3 = m1 + m2;
            Matrix m4 = m1 - m2;
            Console.WriteLine(m1);
            Console.WriteLine(m2);
            Console.WriteLine(m3);
            Console.WriteLine(m4);
            Console.ReadLine();
        }
    }
}

Sealed Classes and Sealed Methods

  • Sealed Classes: A Class which is defined by using the sealed modifier is a sealed class but if any class is declared as sealed the class cannot be inherited by any other class 
           for example:
           sealed class class1
           class2:class1    //Invalid
Note: We can still consume a sealed class from any other class by creating the object even if inheritance is not possible.
  • Sealed Methods: A method which cannot be overridden under child classes is called as Sealed Methods and by default every method of a class is a sealed method because overriding a child class under parent class is possible only when the method is declared as virtual.
            If a method is declared as virtual under a class, any child class of the class linear hierarchy has a right to override the method. 
       class1
       public virtual void show()
       class2:class1    
       public override void show()
       class3:class2
       public override void show()
Note: In the above case even if class2 does not override the method then also class3 can override the method.

Method Overriding

If at all a parent classes method is re-implemented under a child class exactly with the same signature we call it as Method  Overriding.

How to override a parent classes method under child class ?
  • If we want to override any parent classes method under child class first under the parent the method must be defined using virtual modifier. Declaring a method as virtual under a class is giving a permission for its child classes to override.
  • The methods that are declared as virtual can be overwritten as child classes using a override modifier.
      class1
      public virtual void Show()  // overridable
      class 2:class1
      public override void Show() // overriding

Add a class LoadParent.cs and write the following code
using System;
namespace CSharpConsole
{
    class LoadParent
    {
        public void Test()
        {
            Console.WriteLine("Parent's test method");
        }
        public virtual void  Show() //  overridable
        {
            Console.WriteLine("Parent's show method");
        }
        public void Display()
        {
            Console.WriteLine("Parent's display method");
        }
    }
}
// Add a class loadchild.cs and write the following code
using System;
namespace CSharpConsole
{
    class loadchild: LoadParent
    {
       // overloading parent's test method
        public void Test(int x)
        {
            Console.WriteLine("Child's test method ");
        }
       public override  void Show()
        {
            Console.WriteLine("Child's show method ");
        }
       public new void Display()
       {
            Console.WriteLine("Child's display method");
       }
       static void Main()
       {
           loadchild c = new loadchild();
           c.Test();
           c.Test(10);
           c.Show();
           c.Display();
           Console.ReadLine();
       }
   }
}

Types of Polymorphism

Polymorphism is divided into 2 categories
  • Compiletime Polymorphism (also called as Static Polymorphism or Early Binding)
  • Runtime Polymorphism (also called as Non-Static Polymorphism or Late Binding)
        In the first case the object of the class will identify for a particular method call which polymorphic method has to be executed and binds the method call with its method definition and executes this method in runtime but only the method will be bound. This type of binding takes place in Overloading because in overloading we have multiple methods with same name but different signature so each method is unique to itself so while binding the method definition we can identify the unique keyword.
       In the second case ie Runtime Polymorphism the object of a class recognizes which polymorphic method it has to call in runtime and this kind of identification takes pace in Overriding and Hiding as there are multiple methods with the same name and same signature with both the cases so that  the object will identify which exact method has to be executed in runtime only being on the hierarchy of the class.