inheritance and Polymorphism in CSharp

Preview:

Citation preview

  • 7/30/2019 inheritance and Polymorphism in CSharp

    1/5

    Inheritance and Polymorphism

    Inheritance is a technique that allows the use of existing classes as bases for deriving other classes.Polymorphism is the ability of different objects to respond in different ways to the same message.

    When Dhirubhai Ambani died, his sons inherited the business empire. Things are probably in a messtoday for the Reliance companies shareholders. In the world of object oriented programming also,

    there exists the concept of Inheritance. And if not implemented properly, classes derived out ofinheritance may end up having some squabbles of their own, ala Ambanis style.

    InheritanceClasses can be derived from other classes. Classes thus derived will exhibit the data members andmethod members of the parent class depending on access and visibility modifiers. A class whichinherits the wealth of another class is often called the Derived class, and the parent class is calledBase class. Just like you inherit wealth and genes from your forefathers, some languages supportmultiple-inheritance. C# does not support that, and generally adheres to the belief that multiple-inheritance can be a pain to a developer if he is building large applications. Let us now create a classand derive another class from it.

    Code 1

    using System;

    class prime{public int primechecker(int x){if (x == 1){Console.WriteLine("This is neither prime nor composite");return x;

    }else if (x == 2){Console.WriteLine("This is a Prime");return x;}else{int i = 2;double n = Math.Sqrt(x);while (i < n){if ((x % i) == 0)

    {Console.WriteLine("{0} is a NOT prime number", x);return x;}i = i + 1;}Console.WriteLine("{0} is a prime number", x);return x;}}}

    class Derivedclass : prime

    {public void Doublex(int x){int Dub =x+x;Console.WriteLine("The Double of {0} is {1}", x, Dub);}

  • 7/30/2019 inheritance and Polymorphism in CSharp

    2/5

    }

    class Mainclass{public static void Main(){Derivedclass prime1 = new Derivedclass();Console.WriteLine("Enter a number");string y = Console.ReadLine();

    int number = Convert.ToInt32(y);prime1.primechecker(number);prime1.Doublex(number);Console.ReadLine();}}

    What did I do here (Code-1)? I wrote a class called prime with a method called primechecker. Themethod accepts an integer checks whether it is a prime number or not by using the famous algorithmpopularly called Erotosthenes sieve. I will not delve into the algorithm, since it is quite academic andtrivial. I created a class called Derivedclass out of the class prime and then created a method in the

    derived class called Doublex. The class Mainclass contains the Main() method and it instantiates an

    object prime1, and both methods on the object are invoked. Note that one method (primechecker) isinherited from a Base class while the other method (Doublex) is within the Derived class.

    OverridingOverriding literally means riding over and implies an object being provided priority over another. Itmeans giving supremacy over another. In pure OOP terms an object or a method or a class can havesupremacy over another, depending on certain criteria. It is an understatement if I say that C# is oneof the languages that ride on overriding. Consider the example of a class which has three methods.

    You may want to hide one method from derived classes. And at the same time you may want to openthe method to an instance created out of the Base class. How do you achieve this? You use overriding.

    Code 2

    using System;

    class Baseclass{public virtual string Method1(){Console.WriteLine("This is a virtual method");return "This is applicable only to Baseclass";}}

    class Derivedclass: Baseclass{public override string Method1(){Console.WriteLine("The method is overridden");return "This is how C# overrides method from Base classes";}}

    class Mainclass{public static void Main(){

    Baseclass class1 = new Baseclass();Derivedclass class2 = new Derivedclass();class1.Method1();class2.Method1();}

  • 7/30/2019 inheritance and Polymorphism in CSharp

    3/5

    }

    Run the program in Code-2. The method Method1 called by the object class1 instantiated fromBaseclass will invoke the original Method1 and the Method1 called by the second object class2 willoverride the method from the Baseclass. This is called method overriding and C# has a very simpleway to implement the same.

    Method hiding and Polymorphism

    Some of our younger readers will be wondering what is the big deal with the above two examples. Whydo you need to have a virtual method in first place when code is visible in the same window?Unfortunately a serious software project will have more than the few dozen lines of code which wehave written. It will run into thousands of lines of code, which will be written by many developers. The

    code will be split into hundreds of files which may reside across a network or even on a remote server.In such cases, you do not try understanding what the code says in a class; you only look at what allmethods and variables are exposed by the class.

    Most projects will need consistent maintenance and updating. You may have derived a class from aBase class and then written an extra method in the Derived class. Your colleague who has written theBase class one day thinks of some modifications and creates another method inside the Base class,which incidentally has the same name as the method in the Derived class. Suddenly the applicationcrashes generating compilation errors. This is a likely phenomenon in a multi-team project spanning

    over months. C# sorts this out with a simple implementation called polymorphism which meansavailable in many forms.

    Code 3

    using System;

    class Baseclass{public string NewMethod(){

    Console.WriteLine("This is a new method");return " This is a New Method";}}

    class Derivedclass : Baseclass{public new string NewMethod(){Console.WriteLine("This is a method I wrote long time back");return " This is a method I wrote long time back";}}

    class Mainclass{public static void Main(){Derivedclass class1 = new Derivedclass();class1.NewMethod();Console.ReadLine();}}

    I would recommend you to type in the example Code-3 as it is, and then remove the keyword newfrom the method NewMethod inside the Derivedclass. The program will compile, but will produce a

    warning asking you to insert the keyword new. The simple procedure of adding new to a methodinside the Derived class will mean that the method is hidden from the Base class.

    C# also allows classes to be sealed from other classes being derived out of the class. You caninstantiate an object directly out of a sealed class, but no classes can be derived out of it. You use the

  • 7/30/2019 inheritance and Polymorphism in CSharp

    4/5

    modifier sealed to seal a class. An abstract class does not permit you to instantiate, but you canderive classes out of a Base class with modifier as abstract.

    Interfaces and Inheritance

    This is yet another important aspect of Object Oriented Programming. I mentioned that somelanguages, notably Python and C++, let you inherit methods and variables from their hierarchy of baseand derived classes, and this is described as multiple-inheritance. Multiple-inheritance is a great

    feature, but it has its own pitfalls. You can have potential programming errors when you write a largecluster of programs where it is likely that you may have named a few methods common, within aninherited family tree of classes. They may not be compilation errors, but logical errors, which may bemissed even by the eye of your tester. I guess this is one of the reasons why the C# developmentteam, did not explicitly implement multiple-inheritance in the new language. In C#, like Java, thereexists a concept called Interfaces which lets you access information from a chain of inherited classes.

    Code 4

    using System;

    interface IOne{int ShowBalance { get; } //Interface propertyvoid ShowAccount(); //Interface method}

    interface ITwo{string AccountName { get; set; } //Interface propertyvoid ShowInformation(); //Interface method}

    //Multiple Inheritance feature of Interfacespublic class UseBothInterfaces : IOne, ITwo

    {// Field for interface propertyprivate string _AccountName;

    // Property implementationpublic int ShowBalance{get { return 10000; } //Read only value}

    public string AccountName{ //Getter and Setter propertyget { return _AccountName; }

    set { _AccountName = value; }}

    // ShowAccount() method implemented, assigning OwnerNamepublic void ShowAccount() { AccountName = "Dhirubhai Ambani"; }

    // ShowInformation() method implementedpublic void ShowInformation() { }

    public object Show(){//ShowAccount(); // Method called - overrides propertyreturn AccountName + " has in his SBI account " + ShowBalance + " million Rupees";

    }

    class Test{public static void Main(){

  • 7/30/2019 inheritance and Polymorphism in CSharp

    5/5

    UseBothInterfaces Accountstats = new UseBothInterfaces();Accountstats.AccountName = "Mukesh Ambani";Console.Write(Accountstats.Show());}}}

    The example Code-4 is a rehash of an MSDN code. I have just simplified it and it displays two

    Interfaces being created and then these two Interfaces being merged and a class is derived from themerged interfaces. Note that for practical purposes it is a good idea to name an Interface with letter Ias prefix. There are two methods which are derived from the two interfaces. And a third method callsthem. In the program, another class is created which instantiates an object (Accountstats) fromderived class (UseBothInterfaces) and then calls a method (Show). The above example demonstrates

    how you can use Interfaces to create a situation of multiple-inheritance. Therefore, working withinterfaces offers us the ability to implement multiple-inheritance, assign and retrieve property values.