Friday, 22 February 2013

Constructor Overloading

Just like we can overload the methods of a class in the same way we can also overload the constructors of a class i.e it is possible to define multiple constructors under a class changing their signatures.
    If a constructor of a class are overloaded we can create object of that class by making use of any constructor available or we can create a separate object by using a separate constructor.

Add a class LoadCon.cs and write the following code.

// Constructor Overloading

using System;
namespace CSharpConsole
{
    class LoadCon
    {
        int x;
        public LoadCon()     //default constructor
        {
            x = 10;
        }
        public LoadCon(int x)
        {
            this.x = x;

        }
        public void Display()
        {
            Console.WriteLine("The value of x is:{0}",+ x);
        }
        static  void Main()
        {
            LoadCon c1 = new LoadCon();
            LoadCon c2 = new LoadCon(20);
            c1.Display();
            c2.Display();
            Console.ReadLine();
        }
    }
}

Polymorphism

Its an approach of definning different methods with a different behaviour i.e whenever the input changes the output or behaviour also changes accordingly which can be implemented under a language using different approaches like Overloading, Overriding and Hiding.

Overloading
This is again of three types:
  • Method Overloading
  • Constructor Overloadding
  • Operator Overloading 
Method Overloading: It is an approach of definnig multiple methods under a class with the same name, by changing the signature of those methods. Changing the signature of those method in the sense we can change the number of parameters being passed to the method or order of parameters being passed to method.

//Method overloading

using System;

namespace CSharpConsole
{
    class LoadDemo
    {
        public void Show()
        {
            Console.WriteLine(1);
        }
        public void Show( int x)
        {
            Console.WriteLine(2);
        }
        public void Show(string s)
        {
            Console.WriteLine(3);
        }
        public void Show(int x, string s)
        {
            Console.WriteLine(4);
        }
        public void Show(string s, int x)
        {
            Console.WriteLine(5);
        }

        static  void Main()
        {
            LoadDemo d = new LoadDemo();
            d.Show();
            d.Show(10);
            d.Show("hello");
            d.Show(5,"leena");
            d.Show("bansiwal", 15);
            Console.ReadLine();
        }
    }
}