Wednesday, July 2, 2014

Method Overloading, Method Overriding, Method Hiding

Polymorphism
The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'.

Static Polymorphism

 The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding.
 C# provides two techniques to implement static polymorphism. These are:
·    Function overloading or Method overloading
Definition is using the same method name with different type of parameters or different set of parameters is known as Method Overloading.
Or

The process of creating more than one method in a class with same name or creating a method in derived class with same name as a method in base class is called as method overloading.

Overloading (Called as Early Binding or Compile Time Polymorphism or static binding)

classMethod_overloading
    {

        publicintAddition(int a, int b)
        {
            int x;
            returnx = a + b;
        }
        publicintAddition(int a, int b, int c)
        {
            int y;
            returny = a + b + c;
        }

        publicfloatAddition(float a, float b)
        {
            floatu;
            returnu = a + b;
        }

        publicfloatAddition(float a, float b, float c)
        {
            floatv;
            returnv = a + b + c;
        }
    }

    classhub
    {

        publicstaticvoidMain(String[] args)
        {

            Method_overloading mthover = new Method_overloading();
            Console.WriteLine("Addition of two integers::::::::::::::::" + mthover.Addition(2, 5));
            Console.WriteLine("Addition of two double type values::::::" + mthover.Addition(0.40f, 0.50f));
            Console.WriteLine("Addition of three integers::::::::::::::" + mthover.Addition(2, 5, 5));
            Console.WriteLine("Addition of three double type values::::" + mthover.Addition(0.40f, 0.50f, 0.60f));
            Console.ReadLine();
        }

    }


Output:






Output:








Output:


In case of method overloading, compiler identifies which overloaded method to execute based on number of arguments and their data types during compilation itself. Hence method overloading is an example for compile time polymorphism.

Note:

For example, you want to declare a method with name Addition. But you don't have idea about how many parameters has to declare means addition of two numbers or three numbers or etc, and you don't know about what type of data it is? means Int, float

Method overloading is an approach which allows to provide multiple behaviour to a methods,
Example write and writeline methods of console class.
Console.WriteLine(int value);
Console.WriteLine(float value);
Console.WriteLine(boolvalue);


Method overriding

Overriding (Called as Late Binding or Run Time Polymorphism or dynamic binding)





Whereas Overriding means changing the functionality of a method without changing the signature. We can override a function in base class by creating a similar function in derived class. This is done by usingvirtual/override keywords.

If a method of parent class was redefined in the child class with the same signature we called it has method overriding.

Base class method has to be marked with virtual keyword and we can override it in derived class usingoverride keyword.

Derived class method will completely overrides base class method i.e. when we refer base class object created by casting derived class object a method in derived class will be called



public class BaseClass
    {
        public virtual void Method1()
        {
            Console.Write("Base Class Method");
        }
    }
    // Derived class
    public class DerivedClass : BaseClass
    {
        public override void Method1()
        {
            Console.Write("Derived Class Method");
        }
    }
    // Using base and derived class
    public class Sample
    {
        public static void Main(String[] args)
        {
            DerivedClass objDC = new DerivedClass();
            objDC.Method1();
            // calling the baesd class method
            BaseClass objBC = (BaseClass)objDC;
            objDC.Method1();
            Console.ReadKey();
        }
    }


output:

Derived Class Method

Derived Class Method





output:
method1
method 4
method 3




output:
method 2
method 4




output:
method 4
method 4


2. Using the base keyword also we can call the virtual methods of the parent from the child class.
Note: using the base keyword is not allowed from static blocks like Main.

-To test this do the following:
   i) Add a new method under the child class LoadChild as PTest which will internally call the virtual method of the parent.
          public void PTest(int x)
          {
               base.Test(x);
          }

   ii) Now from the Main method of the child class LoadChild u can call all the methods by using the object of the child class only as following:
          LoadChild c = new LoadChild();
          c.Test();              //Calls Parent Method
          c.PTest(10);       //Calls Parent Method
          c.Test("Hello");  //Calls Child Method
          c.Test(10);         //Calls Child




class LoadParent
    {
        public voidTest()
        {
            Console.WriteLine("Method1");
        }
        public virtualvoid Test(intx)
        {
            Console.WriteLine("Method2");
        }
    }
    class LoadChild:LoadParent
    {
        public overridevoid Test(intx)
        {
            Console.WriteLine("method4");
        }
        public voidPTest(int x)
        {
            base.Test(x);
        }
        static voidMain(string[] args)
        {
            LoadChildc = new LoadChild();
            c.PTest(10);
            c.Test(10);
            Console.ReadKey();
        }
       
    }
       
    }


OUTPUT:

METHOD2

METHOD4

Method Hiding
Can we rewrite a method under a child class without permission from parent?
Yes, we can rewrite a method under the child without the permission of parent also (i.e. not declared as virtual).But we called this as Method Hiding.
Method overriding and Method Hiding were similar type of approaches where in the first case we rewrite a method under child which is declared as virtual in parent, where as in the second case, we rewrite a method under child which we not declared as virtual in parent.

In case of overriding, we use the override modifier to rewrite the method.
Where as in case of hiding we use the new modifier for rewriting the method.

Public void Test()
Public new void Test()         


Method overloading
Method overriding
Method Hiding
dividing multiple behaviors to a method
changing the behavior of a Method under child class with a permission from parent
Changing the behavior of Method under child class without permission from parent.


Method overloading
method overriding
this allows defining multiple methods with the same name by changing their signature
this allows defining multiple methods with same name and same signature
this can be performed with in a class or with in a child class
this can be performed only within a child class
when performed under the child class does not require any permission from parent
to perform this we require an explicit permission from parent.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Tom
{
    class TOM
    {
        public void Display()
        {
            System.Console.WriteLine("TOM::Display");
        }
    }
    class JOY : TOM
    {
        public new void Display()
        {
            System.Console.WriteLine("JOY::Display");
            Console.ReadLine();
        }
    }
    class Show
    {
        public static void Main()
        {
            JOY obj = new JOY();
            obj.Display();
        }
    }
}






If a method Test() is declared in the base class A and classes B or C has no methods as shown below.
using System;
namespace Polymorphism
{
 class A
 {
 public void Test() { Console.WriteLine("A::Test()"); }
 }

 class B : A { }

 class C : B { }

 class Program
 {
 static void Main(string[] args)
 {
 A a = new A();
 a.Test(); // output --> "A::Test()"

 B b = new B();
 b.Test(); // output --> "A::Test()"

 C c = new C();
 c.Test(); // output --> "A::Test()"

 Console.ReadKey();

 }
 }
}


Suppose you have Test() method in all the classes A, B, C as shown below:
using System;
namespace Polymorphism
{
 class A
 {
 public void Test() { Console.WriteLine("A::Test()"); }
 }

 class B : A
 {
 public void Test() { Console.WriteLine("B::Test()"); }
 }

 class C : B
 {
 public void Test() { Console.WriteLine("C::Test()"); }
 }

 class Program
 {
 static void Main(string[] args)
 {

 A a = new A();
 B b = new B();
 C c = new C();

 a.Test(); // output --> "A::Test()"
 b.Test(); // output --> "B::Test()"
 c.Test(); // output --> "C::Test()"

 a = new B();
 a.Test(); // output --> "A::Test()"

 b = new C();
 b.Test(); // output --> "B::Test()"

 Console.ReadKey();
 }
 }
}

When you will run the above program, it will run successfully and gives the O/P. But this program will show the two warnings as shown below:

'Polymorphism.B.Test()' hides inherited member 'Polymorphism.A.Test()'. Use the new keyword if hiding was intended.

'Polymorphism.C.Test()' hides inherited member 'Polymorphism.B.Test()'. Use the new keyword if hiding was intended.




Method Hiding (new keyword)

As you have seen in the above example the compiler generate the warnings since C# also supports method hiding. For hiding the base class method from derived class simply declare the derived class method with new keyword. Hence above code can be re-written as :

using System;

namespace Polymorphism
{
 class A
 {
 public void Test() { Console.WriteLine("A::Test()"); }
 }

 class B : A
 {
 public new void Test() { Console.WriteLine("B::Test()"); }
 }

 class C : B
 {
 public new void Test() { Console.WriteLine("C::Test()"); }
 }

 class Program
 {
 static void Main(string[] args)
 {

 A a = new A();
 B b = new B();
 C c = new C();

 a.Test(); // output --> "A::Test()"
 b.Test(); // output --> "B::Test()"
 c.Test(); // output --> "C::Test()"

 a = new B();
 a.Test(); // output --> "A::Test()"

 b = new C();
 b.Test(); // output --> "B::Test()"

 Console.ReadKey();
 }
 }
}

Moreover, if you are expecting the fourth and fifth output should be "B::Foo()" and "C::Foo()" since the objects a and b are referenced by the object of B and C respectively then you have to re-write the above code for Method Overriding.



Method Overriding (virtual and override keyword)
In C#, for overriding the base class method in derived class, you have to declare base class method as virtual and derived class method as override as shown below:
using System;
namespace Polymorphism
{
 class A
 {
 public virtual void Test() { Console.WriteLine("A::Test()"); }
 }

 class B : A
 {
 public override void Test() { Console.WriteLine("B::Test()"); }
 }

 class C : B
 {
 public override void Test() { Console.WriteLine("C::Test()"); }
 }

 class Program
 {
 static void Main(string[] args)
 {

 A a = new A();
 B b = new B();
 C c = new C();
 a.Test(); // output --> "A::Test()"
 b.Test(); // output --> "B::Test()"
 c.Test(); // output --> "C::Test()"

 a = new B();
 a.Test(); // output --> "B::Test()"

 b = new C();
 b.Test(); // output --> "C::Test()"

 Console.ReadKey();
 }
 }
}




Mixing Method Overriding and Method Hiding
You can also mix the method hiding and method overriding by using virtual and new keyword since the method of a derived class can be virtual and new at the same time. This is required when you want to further override the derived class method into next level as I am overriding Class B, Test() method in Class C as shown below:
using System;
namespace Polymorphism
{
 class A
 {
 public void Test() { Console.WriteLine("A::Test()"); }
 }

 class B : A
 {
 public new virtual void Test() { Console.WriteLine("B::Test()"); }
 }

 class C : B
 {
 public override void Test() { Console.WriteLine("C::Test()"); }
 }

 class Program
 {
 static void Main(string[] args)
 {

 A a = new A();
 B b = new B();
 C c = new C();

 a.Test(); // output --> "A::Test()"
 b.Test(); // output --> "B::Test()"
 c.Test(); // output --> "C::Test()"

 a = new B();
 a.Test(); // output --> "A::Test()"

 b = new C();
 b.Test(); // output --> "C::Test()"

 Console.ReadKey();
 }
 }
}
Note
The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allow it to be overridden in the derived class.
The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or event of base class into derived class.
The new keyword is used to hide a method, property, indexer, or event of base class into derived class.






Can we restrict a method not to be overridden under the child class?
If you want to do restrict a method not to be overridden by a child classes it should not be declared as sealed but every method by default sealed unless it was declared as virtual.

If a method is declared as virtual under parent can any child class overwrite it
Yes, if a method is declared as virtual in parent any child class as a write to overwrite it.

Parent class 1
Public virtual void Test ()

Child class 2
Public override void Test ()

Child class 3
Public override void Test ()

Can we restrict further overriding of a method at a child class which was declared as virtual in its parent
Yes, this can be performed by using sealed modifier on the method while overriding.

Public  virtual void Test()

Public sealed override void Test()


Public override void Test()



Dynamic Polymorphism

When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime.
Dynamic polymorphism is implemented by abstract classes and virtual functions.


classShape
    {
protectedintwidth, height;
publicShape(int a = 0, int b = 0)
        {
width = a;
height = b;
        }
publicvirtualintarea()
        {
Console.WriteLine("Parent class area :");
return0;
        }
    }
classRectangle : Shape
    {
publicRectangle(int a = 0, int b = 0)
            : base(a, b)
        {

        }
publicoverrideintarea()
        {
Console.WriteLine("Rectangle class area :");
return(width * height);
        }
    }
classTriangle : Shape
    {
publicTriangle(int a = 0, int b = 0)
            : base(a, b)
        {

        }
publicoverrideintarea()
        {
Console.WriteLine("Triangle class area :");
return(width * height / 2);
        }
    }
classCaller
    {
publicvoidCallArea(Shapesh)
        {
int a;
            a = sh.area();
Console.WriteLine("Area: {0}", a);
        }
    }
classTester
    {

staticvoidMain(string[] args)
        {
Callerc = newCaller();
Rectangler = newRectangle(10, 7);
Trianglet = newTriangle(10, 5);
c.CallArea(r);
c.CallArea(t);
Console.ReadKey();
        }
    }


Output:



Conclusion

Compile time Polymorphism
·         Compile time Polymorphism also known as method overloading

·         Method overloading means having two or more methods with the same name but with different signatures


Example of Compile time polymorphism



Run time Polymorphism
·         Run time Polymorphism also known as method overriding
·         Method overriding means having two or more methods with the same name , same signature but with different implementation
Example of Run time Polymorphism



Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...