Você está na página 1de 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 mess today 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 of inheritance may end up having some squabbles of their own, ala Ambanis style.

Inheritance
Classes can be derived from other classes. Classes thus derived will exhibit the data members and method members of the parent class depending on access and visibility modifiers. A class which inherits the wealth of another class is often called the Derived class, and the parent class is called Base class. Just like you inherit wealth and genes from your forefathers, some languages support multiple-inheritance. C# does not support that, and generally adheres to the belief that multipleinheritance can be a pain to a developer if he is building large applications. Let us now create a class and 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); }

} 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. The method accepts an integer checks whether it is a prime number or not by using the famous algorithm popularly called Erotosthenes sieve. I will not delve into the algorithm, since it is quite academic and trivial. 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 (primeche cker) is inherited from a Base class while the other method (Doublex) is within the Derived class.

Overriding
Overriding literally means riding over and implies an object being provided priority over another. It means giving supremacy over another. In pure OOP terms an object or a method or a class can have supremacy over another, depending on certain criteria. It is an understatement if I say that C# is one of 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 open the 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(); }

Run the program in Code-2. The method Method1 called by the object class1 instantiated from Baseclass will invoke the original Method1 and the Method1 called by the second object class2 will override the method from the Baseclass. This is called method overriding and C# has a very simple way 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. Why do 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 we have 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 all methods and variables are exposed by the class. Most projects will need consistent maintenance and updating. You may have derived a class from a Base class and then written an extra method in the Derived class. Your colleague who has written the Base 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 application crashes 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 means available 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 new from 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 method inside 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 can instantiate an object directly out of a sealed class, but no classes can be derived out of it. You use the

modifier sealed to seal a class. An abstract class does not permit you to instantiate, but you can derive 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 some languages, notably Python and C++, let you inherit methods and variables from their hierarchy of base and 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 large cluster of programs where it is likely that you may have named a few methods common, within an inherited family tree of classes. They may not be compilation errors, but logical errors, which may be missed even by the eye of your tester. I guess this is one of the reasons why the C# development team, did not explicitly implement multiple-inheritance in the new language. In C#, like Java, there exists 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 property void ShowAccount(); //Interface method } interface ITwo { string AccountName { get; set; } //Interface property void ShowInformation(); //Interface method } //Multiple Inheritance feature of Interfaces public class UseBothInterfaces : IOne, ITwo { // Field for interface property private string _AccountName; // Property implementation public int ShowBalance { get { return 10000; } //Read only value } public string AccountName { //Getter and Setter property get { return _AccountName; } set { _AccountName = value; } } // ShowAccount() method implemented, assigning OwnerName public void ShowAccount() { AccountName = "Dhirubhai Ambani"; } // ShowInformation() method implemented public void ShowInformation() { } public object Show() { //ShowAccount(); // Method called - overrides property return AccountName + " has in his SBI account " + ShowBalance + " million Rupees"; } class Test { public static void Main() {

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 the merged interfaces. Note that for practical purposes it is a good idea to name an Interface with letter I as prefix. There are two methods which are derived from the two interfaces. And a third method calls them. In the program, another class is created which instantiates an object (Accountstats) from derived 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 with interfaces offers us the ability to implement multiple-inheritance, assign and retrieve property values.

Você também pode gostar