Wednesday, 4 April 2012

OOPS Concept -3 (Overloading and Overriding)

Overloading ---------->




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

namespace TestOOPSConcept
{
    /// <summary>
    /// In Same class, u define funtion with same name,parameter then amniguity error comes.
    /// </summary>
    class TestOverloading
    {

        static void Foo(int x)
        {
            Console.WriteLine("Foo(int x)");
        }

        static void Foo(string y)
        {
            Console.WriteLine("Foo(string y)");
        }

        static void Foo(double z)
        {
            Console.WriteLine("Foo(double y)");
        }

        static void Foo(int x, int y = 5)
        {
            Console.WriteLine("Foo(int x, int y = 5)");
        }

   
        //static void Main()
        //{

        //    Foo(10, 5);
        //    Console.Read();
        //}

    }
}






Overriding ------------------->



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

namespace TestOOPSConcept
{
    /// <summary>
    ///  /// overriding and Hiding
    /// The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class.
    /// virtual or abstract members cannot be private
    /// You cannot use the virtual modifier with the static, abstract, private or override modifiers.
    /// </summary>
    class A
    {
        public void Foo()
        {
            Console.WriteLine("A::Foo()");
        }
    }

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

    class Test
    {
        //static void Main(string[] args)
        //{
        //    A a;
        //    B b;

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

        //    a = new B();
        //    a.Foo();  // output --> "A::Foo()"
        //    Console.Read();
        //}
    }
}

No comments:

Post a Comment