.NETFramework Concepts - part2

 Polymorphism

Polymorphism means having more than one form.Overloading and overriding are used to implement polymorphism. 

Polymorphism is classified into compile time polymorphism or early binding or static binding and Runtime polymorphism or late binding or dynamic binding.

The polymorphism in which compiler identifies which polymorphic form it has to execute at compile time it self is called as compile time polymorphism or early binding. Advantage of early binding is execution will be fast. Because every thing about the method is known to compiler during compilation it self and disadvantage is lack of flexibility. Examples of early binding are overloaded methods, overloaded operators and overridden methods that are called directly by using derived objects.

The polymorphism in which compiler identifies which polymorphic form to execute at runtime but not at compile time is called as runtime polymorphism or late binding. Advantage of late binding is flexibility and disadvantage is execution will be slow as compiler has to get the information about the method to execute at runtime. Example of late binding is overridden methods that are called using base class object.

Method Overloading in C#.NET

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. In VB.net when you are overloading a method of the base class in derived class, then you must use the keyword “Overloads”. But in C# no need to use any keyword while overloading a method either in same class or in derived class. While overloading methods, a rule to follow is the overloaded methods must differ either in number of arguments they take or the data type of at least one argument.

Example : The following example creates two classes Class1 and Class2 where Class2 is inherited from Class1 and it overloads the method Sum available in Class1.

Write program to illustrate method overloading in C#.NET? 

namespace Inheritance

{

    class Class1

    {

        public int Sum(int A, int B)

        {

            return A + B;

        }

    }

    class Class2 : Class1

    {

        public int Sum(int A, int B, int C)

        {

            return A + B + C;

        }

    }

    class MethodOL

    {

        static void Main()

        {

            Class2 C = new Class2();

            Console.WriteLine(C.Sum(10, 20));

            Console.WriteLine(C.Sum(10, 20, 30));

        }

    }

}

Example: The following example creates two classes with the name Maths1 and Maths2 where Maths2 is inherited from Maths1 and overloads a method Sum of Maths1.

namespace Inheritance

{

    class Maths1

    {

        public int Sum(params int[] A)

        {

            int S = 0;

            foreach (int n in A)

            {

                S += n;

            }

            return S;

        }

    }

    class Maths2 : Maths1

    {

        public float Sum(params float[] A)

        {

            float S = 0;

            foreach (float n in A)

            {

                S += n;

            }

            return S;

        }

    }

    class MethodOL1

    {

        static void Main()

        {

            Maths2 M = new Maths2();

            int[] A = { 23, 44, 56, 71, 90 };

            float[] F = { 34.23F, 17.23F, 19.99F, 14.76F, 21.21F };

            Console.WriteLine(M.Sum(A));

            Console.WriteLine(M.Sum(F));           

        }

    }

}

Method overloading provides more than one form for a method. Hence it is an example for polymorphism. In case of method overloading, compiler identifies which overloaded method to execute based on number of arguments and their data types during compilation it self. Hence method overloading is an example for compile time polymorphism.

Method Overriding in C#.NET

Creating a method in derived class with same signature as a method in base class is called as method overriding. Same signature means methods must have same name, same number of arguments and same type of arguments. Method overriding is possible only in derived classes, but not within the same class. When derived class needs a method with same signature as in base class, but wants to execute different code than provided by base class then method overriding will be used. To allow the derived class to override a method of the base class, C# provides two options, virtual methods and abstract methods.

Virtual Methods in C#.NET

When you want to allow a derived class to override a method of the base class, within the base class method must be created as virtual method and within the derived class method must be created using the keyword override. When a method declared as virtual in base class, then that method can be defined in base class and it is optional for the derived class to override that method. When it needs same definition as base class, then no need to override the method and if it needs different definition than provided by base class then it must override the method.

Example : The following example creates three classes shape, circle and rectangle where circle and rectangle are inherited from the class shape and overrides the methods Area() and Circumference() that are declared as virtual in Shape class.

Write a program to illustrate method overriding in C#.NET

namespace Inheritance

{

    class Shape

    {

        protected float R, L, B;

        public virtual float Area()

        {

            return 3.14F * R * R;

        }

        public virtual float Circumference()

        {

            return 2 * 3.14F * R;

        }

    }

    class Rectangle : Shape

    {

        public void GetLB()

        {

            Console.Write("Enter Length : ");

            L = float.Parse(Console.ReadLine());

            Console.Write("Enter Breadth : ");

            B = float.Parse(Console.ReadLine());

        }

        public override float Area()

        {

            return L * B;

        }

        public override float Circumference()

        {

            return 2 * (L + B);

        }

    }

    class Circle : Shape

    {

        public void GetRadius()

        {

            Console.Write("Enter Radius : ");

            R = float.Parse(Console.ReadLine());

        }

    }

    class VirtualMethods

    {

        static void Main()

        {

            Rectangle R = new Rectangle();

            R.GetLB();

            Console.WriteLine("Area : {0}", R.Area());

            Console.WriteLine("Circumference : {0}", R.Circumference());

            Console.WriteLine();

            Circle C = new Circle();

            C.GetRadius();

            Console.WriteLine("Area : {0}", C.Area());

            Console.WriteLine("Circumference : {0}", C.Circumference());

        }

    }

}

Method overriding also provides more than one form for a method. Hence it is also an example for polymorphism. When overridden methods are directly called using derived object as in previous example, then it will be an example for compile time polymorphism. Because based on the type of derived object, during compilation it self compiler identifies which overridden method it has to execute.

Abstract Methods And Abstract Classes in C#.NET

Another way for method overriding is abstract methods. There may be a situation where it is not possible to define a method in base class and every derived class must override that method. In this situation abstract methods are used. When a method is declared as abstract in the base class then it is not possible to define it in the base class and every derived class of that class must provide its own definition for that method. When a class contains at least one abstract method, then the class must be declared as abstract class. When a class is declared as abstract class, then it is not possible to create an instance for that class. But it can be used as a parameter in a method.

Example : The following example creates three classes shape, circle and rectangle where circle and rectangle are inherited from the class shape and overrides the methods Area() and Circumference() that are declared as abstract in Shape class and as Shape class contains abstract methods it is declared as abstract class.

Write a program to illustrate In C#.NET? 

namespace Inheritance

{

    abstract class Shape1

    {

        protected float R, L, B;

        public abstract float Area();

        public abstract float Circumference();

    }

    class Rectangle1 : Shape1

    {

        public void GetLB()

        {

            Console.Write("Enter Length : ");

            L = float.Parse(Console.ReadLine());

            Console.Write("Enter Breadth : ");

            B = float.Parse(Console.ReadLine());

        }

        public override float Area()

        {

            return L * B;

        }

        public override float Circumference()

        {

            return 2 * (L + B);

        }

    }

    class Circle1 : Shape1

    {

        public void GetRadius()

        {

            Console.Write("Enter Radius : ");

            R = float.Parse(Console.ReadLine());

        }

        public override float Area()

        {

            return 3.14F * R * R;

        }

        public override float Circumference()

        {

            return 2 * 3.14F * R;

        }

    }

    class AbstractMethods

    {

        public static void Calculate(Shape1 S)

        {

            Console.WriteLine("Area : {0}", S.Area());

            Console.WriteLine("Circumference : {0}", S.Circumference());

        }

        static void Main()

        {

            Rectangle1 R = new Rectangle1();

            R.GetLB();

            Calculate(R);

           Console.WriteLine();

            Circle1 C = new Circle1();

            C.GetRadius();

            Calculate(C);

        }

    }

}

In the above example method calculate takes a parameter of type Shape1 from which rectangle1 and circle1 classes are inherited. A base class type parameter can take derived class object as an argument. Hence the calculate method can take either rectangle1 or circle1 object as argument and the actual argument in the parameter S will be determined only at runtime and hence this example is an example for runtime polymorphism.

Sealed Methods

The virtual nature of a method persists for any number of levels of inheritance. For example there is a class “A” that contains a virtual method “M1”. Another class “B” is inherited from “A” and another class “C” is inherited from “B”. In this situation class “C” can override the method “M1” regardless of whether class “B” overrides the method “M1”. At any level of inheritance, if you want to restrict next level of derived classes from overriding a virtual method, then create the method using the keyword sealed along with the keyword override.

            [Access Modifier] sealed override returntype methodname([Params])

            {


            }

Sealed Classes in C#.NET

When you want to restrict your classes from being inherited by others you can create the class as sealed class. To create a class as sealed class, create the class using the keyword sealed.

            [Access Modifier] sealed class classname

            {


            }

New

There may be a situation where you are creating a class in your application that is inherited from a class available in a class library referred by your application and you want to override a method of the base class in derived class and that method was not declared as virtual or abstract in the base class. In this situation you can hide the method of base class by creating a method in derived class with same signature as in base class by using the keyword new.

base

When you want to invoke a method of the base class that is overridden or hidden by the derived class then use the keyword base.

Comparison Between C#.Net And VB.Net in Keywords Related to Inheritance And Polymorphism


 C#.Net                                               VB.Net

Virtual Methods                                Overridable Methods

Abstract Methods                             MustOverride Methods

Abstract Classes                              MustInherit Classes

Override                                             Overrides

Sealed Methods                                NotOverridable Methods

Sealed Classes                                  NotInheritable Classes

New                                                    Shadows

Base                                                   MyBase


Interfaces in C#.NET

An interface is a user defined type that contains only declarations of properties, methods and events and not implementation. Main purpose of interfaces is to provide support for multiple inheritance, which is not possible using classes. A class can implement more than one interface and when a class implements an interface then it must provide definition for each and every member of the interface. An interface is created using the keyword interface and has the following syntax.

[Access Modifier] interface interfacename

{

}

An interface has the following restrictions.

It can not contain fields.

It can contain only member declarations and not definition.

It can not contain static members.

It is not possible to specify access modifier for the members and by default members are public.

To implement an interface in a class, syntax is same as inheriting a class and is as follows.

[Access Modifier] class classname : interface1, interface2,…

{

}

Example : The following example creates two interfaces interface1 and interface2 that implemented in a class with the name Test

namespace Inheritance

{

    interface interface1

    {

        void M1();       

    }

    interface interface2

    {

        void M2();      

    }

    class Test : interface1, interface2

    {

        public void M1()

        {

            Console.WriteLine("M1 Of Interface1");

        }

        public void M2()

        {

            Console.WriteLine("M2 Of Interface2");

        }

    }

    class interfaces

    {

        static void Main()

        {

            Test T = new Test();

            T.M1();

            T.M2();

        }

    }

}

Members with same Signature

There may be a situation where two interfaces contain a member with same signature and those two interfaces are implemented in the same class. In this situation to differentiate the definition of those members in class, you must qualify the member name with interface name and in this case no need to specify access modifier for this member even in class. To call these members first you have to create an instance for the class and then type cast the instance to interface, whose member you want to call.

 Example : The following example creates two interfaces interface1 and interface2 where both contain a method M1 with same signature and are implemented in a class with the name Test.

namespace Inheritance

{

    interface interface3

    {

        void M1();

    }

    interface interface4

    {

        void M1();

    }

    class Test1 : interface3, interface4

    {

        void interface3.M1()

        {

            Console.WriteLine("M1 Of interface3");

        }

       void interface4.M1()

        {

            Console.WriteLine("M1 Of interface4");

        }

    }

    class interfacesamesign

    {

        static void Main()

        {

            Test1 T = new Test1();

            interface3 i3 = (interface3)T;

            i3.M1();

            interface4 i4 = (interface4)T;

            i4.M1();

        }

    }

}

Inheriting a Class And Implementing Interfaces

There may be a situation where you have to create a class by inheriting another class and at the same time implementing one or more interfaces. In this situation you must specify the base class name first and then interface names.           

[Access Modifier] class ClassName : BaseClassName, interface1, interface2, …

{


}

Differences Between Abstract Class And Interface

Abstract Class
Interface
It can contain Fields
It can not contain fields
It can contain members with definition when they are not declared as abstract.
It can not contain definition for any member
You can specify access modifier for the members.
It is not possible to specify an access modifier for the members.
By default members are private.
By default members are public.
It can contain static members
It can not contain static members.
It can contain constructors and destructor
It can not contain constructors and destructor.
It doesn’t support multiple inheritance.
It supports multiple inheritance.

                                                           For Part1 Click here

                                                           For Part3 Click here

Thanks for visiting this blog. How is the content?. Your comment is great gift to my work. Cheers.

No comments:

Post a Comment