Wednesday, December 9, 2015

Method Overriding VS Method Hiding

My previous two articles explained method hiding and method overriding.
In this article we will see the differences between the two with an example.

In my project, I created a ParentClass with a method named “ParentMethod”. I have also created a child class named “ChildClass” that is inheriting from the parent class.
  1. using System;  
  2.   
  3. namespace MethodOverridingMethodHiding {  
  4.     class ParentClass {  
  5.         public void ParentMethod() {  
  6.             Console.WriteLine("I am a parent method");  
  7.         }  
  8.     }  
  9.   
  10.     class ChildClass : ParentClass {  
  11.   
  12.     }  
  13. }  
Let's look at method overriding first
To override a base class method, we need to make that method “virtual”.

  1. class ParentClass {  
  2.         public virtual void ParentMethod() {  
  3.             Console.WriteLine("I am a parent method");  
  4.         }  
  5.     }  
To override the method in our child class, we type override then space then select the method and press Enter.

override

It will generate the following code.
  1. class ChildClass : ParentClass {  
  2.      public override void ParentMethod() {  
  3.          base.ParentMethod();  
  4.      }  
  5.  }  
We can remove the default implementation and provide our own.
  1. class ChildClass : ParentClass {  
  2.     public override void ParentMethod() {  
  3.         Console.WriteLine("I am overriding the parent class method");  
  4.     }  
  5. }  
The next step is to create an instance of our class by using a base class reference variable pointing to the child class object in our main method.
  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         ParentClass pc = new ChildClass();  
  4.         pc.ParentMethod();  
  5.     }  
  6. }  
Run the application

application

Now let's look at an example where we will hide the base method rather than overriding it.

First, we need to remove the virtual keyword from the ParentMethod.
  1. class ParentClass {  
  2.     public void ParentMethod() {  
  3.         Console.WriteLine("I am a parent method");  
  4.     }  
  5. }  
Second, we need to remove the override keyword and add a new keyword.
  1. class ChildClass : ParentClass {  
  2.     public new void ParentMethod() {  
  3.         Console.WriteLine("I am overriding the parent class method");  
  4.     }  
  5. }  
In our main method, we will again create an instance of our ChildClass class by creating a base class reference variable pointing to the child class.
  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         ParentClass pc = new ChildClass();  
  4.         pc.ParentMethod();  
  5.     }  
  6. }  
Run the program
The hidden parent class method will be invoked.

Run the program

Note
But if you want to invoke the child class method, we can do the following in the main method:
  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         ChildClass cc = new ChildClass();  
  4.         cc.ParentMethod();  
  5.     }  
  6. }  
output

From the preceding two examples it is very clear that in method overriding, a base class reference variable pointing to a child class object will invoke the overridden method in the child class and in method hiding, a base class reference variable pointing to a child class object will invoke the hidden method in the base class.

 Overriding

Method overriding is an important feature of OOP that allows us to re-write a base class function or method with a different definition. Overriding is also known as “Dynamic polymorphism” because overriding is resolved at runtime. Here the signature of the method or function must be the same. In other words both methods (base class method and child class method) have the same name, same number and same type of parameter in the same order with the same return type. The overridden base method must be virtual, abstract or override.

Example

  1. public class BaseClass  
  2. {  
  3.     public virtual string GetMethodOwnerName()  
  4.     {  
  5.        return “Base Class”;  
  6.     }  
  7. }  
  8. public class ChildClass : BaseClass  
  9. {  
  10.    public override string GetMethodOwnerName()  
  11.    {  
  12.        return “Child Class”;  
  13.    }  
A method cannot be overriden if:
  • Methods have a different return type
  • Methods have a different access modifier
  • Methods have a different parameter type or order
  • Methods are non virtual or static
Shadowing (method hiding)
A method or function of the base class is available to the child (derived) class without the use of the "overriding" keyword. The compiler hides the function or method of the base class. This concept is known as shadowing or method hiding. In the shadowing or method hiding, the child (derived) class has its own version of the function, the same function is also available in the base class.

Example
  1. Public class BaseClass  
  2. {  
  3.     public string GetMethodOwnerName()  
  4.     {  
  5.        return "Base Class";  
  6.     }  
  7. }  
  8. public class ChildClass : BaseClass  
  9. {  
  10.     public new string GetMethodOwnerName()  
  11.     {  
  12.        return "ChildClass";  
  13.     }  
Test Code
  1. static void Main(string[] args)  
  2. {  
  3.     ChildClass c = new ChildClass();  
  4.     Console.WriteLine(c.GetMethodOwnerName());  
Output
Output

If we do not use the new keyword the compiler generates the warning:

compiler generate warning

Mixing Method (Overriding and shadowing (Method Hiding))

We can also use shadowing and method overriding together using the virtual and new keywords. This is useful when we want to further override a method of the child (derived) class.

Example
  1. public class BaseClass  
  2. {  
  3.     public virtual string GetMethodOwnerName()  
  4.     {  
  5.         return "Base Class";  
  6.     }  
  7. }  
  8. public class ChildClass : BaseClass  
  9. {  
  10.     public new virtual string GetMethodOwnerName()  
  11.     {  
  12.         return "ChildClass";  
  13.     }  
  14. }  
  15. public class SecondChild : ChildClass  
  16. {  
  17.     public override virtual string GetMethodOwnerName()  
  18.     {  
  19.         return "Second level Child";  
  20.     }  
Shadowing Vs Overriding
Shadowing Overriding
Shadowing is a VB.Net concept. It also known as method hiding in C#. Using this concept we can provide a new implementation for the base class method without overriding it. Overriding allows us to re-write a base class function with a different definition.
Using the “new” keyword we can do the shadowing or method hiding. C# uses the virtual/abstract and override keyword for method overriding.
Shadowing redefines an entire method or function. Overriding redefines only the implementation of a method or function.
Showing is used to protect against subsequent base class modification. Overriding does polymorphism by defining a different implementation.
We can change the access modifier. We cannot change the access modifier. The access modifier must be the same as in the base class method or function.
There is no control of a base class on shadowing. In other words, a base class element cannot enforce or stop shadowing. The base class has some control over the overriding. Using the keyword abstract, the base class forces the child (derived) class to implement the function or method.
Shadowing an element (function method or property) can be inherited further in a child (derived) class. The shadowed element is still hidden. The same as shadowing, overriding an element is inherited further in a derived class and the overridden element is still overridden.
In shadowing, the signature of an element could be different. In overriding, the signature of the element must be the same.
In shadowing, the base class cannot access the newly created child (derived) class method. This is because the base class has the same name of the element.
In concept, the base class can be accessed using the child object's overridden method.
Shadowing  Example
  1. static void Main(string[] args)  
  2. {  
  3.     BaseClass c = new ChildClass();  
  4.     Console.WriteLine(c.GetMethodOwnerName());  
Output

Shadow

In overriding, the base class can be accessed using the child object's overridden method.

Overriding Example
  1. static void Main(string[] args)  
  2. {  
  3.     BaseClass c = new ChildClass();  
  4.     Console.WriteLine(c.GetMethodOwnerName());  
Output

Overriding

We cannot use the new and override keywords together. If you do then the compiler throws a compilation error.

Output

compilation error

Methods Overloading Vs Method Overriding Vs Method Hiding in C#

Introduction
Method overloading, method overriding and method hiding are very beautiful features in C# but at the same time they are very confusing for beginners. This article is for beginners to understand these concepts.

Methods Overloading
The method overloading feature in C# is very helpful in code reusability by creating a different version of a method, meaning method overloading is nothing but a technique to create two or more methods of the same name but different signatures.

Same name but different signatures
Method / Function overloading is multiple methods in a class with the same name but different signatures.

The following is a C# method:
  1. public static void myMethod(int a, int b)  
  2. {  
  3. Console.WriteLine("myMethod Version 1 is printed");  

A method signature indicates the number of parameters, types of parameters or kinds of method parameters used for creating an overloaded version of a method. An important point is the return type of the method is not includeed in the signature, meaning if we try to create the method with the same but different return type then we will get a complier error message.
  1. // Number of parameter  
  2.   
  3. public static void myMethod(int a, int b, int c)  
  4. {  
  5. Console.WriteLine("myMethod Version 2 is printed");  
  6.   
  7. }  
  8. // Type of parameters  
  9.   
  10. public static void myMethod(float a, float b, float c)  
  11. {  
  12. Console.WriteLine("myMethod Version 3 is printed");  
  13. }  
  14.   
  15. public static void myMethod(float a, int b, float c)  
  16. {  
  17. Console.WriteLine("myMethod Version 4 is printed");  
  18. }  
  19. // Method parameter  
  20.   
  21. public static void myMethod(float a, out int b, float c)  
  22. {  
  23. Console.WriteLine("b={0} , myMethod Version 5 is printed");  
  24. b =(int)(a + c);  
Here in the following we can see that the 5 versions of various methods are available with the same name but different signatures.

 
Sample Code
  1. namespace MethodOverloading  
  2. {  
  3. class Program  
  4. {  
  5. static void Main(string[] args)  
  6. {  
  7. myMethod(4,4);  
  8. }  
  9.   
  10. public static void myMethod(int a, int b)  
  11. {  
  12. Console.WriteLine("myMethod Version 1 is printed");  
  13. }  
  14. // Number of parameter  
  15.   
  16. public static void myMethod(int a, int b, int c)  
  17. {  
  18. Console.WriteLine("myMethod Version 2 is printed");  
  19. }  
  20. // Type of parameters  
  21.   
  22. public static void myMethod(float a, float b, float c)  
  23. {  
  24. Console.WriteLine("myMethod Version 3 is printed");  
  25. }  
  26.   
  27. public static void myMethod(float a, int b, float c)  
  28. {  
  29. Console.WriteLine("myMethod Version 4 is printed");  
  30. }  
  31. // Method parameter  
  32.   
  33. public static void myMethod(float a, out int b, float c)  
  34. {  
  35. Console.WriteLine("b={0} , myMethod Version 5 is printed");  
  36. b =(int)(a + c);  
  37. }  
  38.   
Method Overriding
Method overriding is nothing but a feature by which a derived class can provide a new implementation for the base class method having the same name and signature as in a derived class. A derived class method can be overridden using the keyword override and that must be virtual or abstract in the base class.
Base Class
  1. public class cars  
  2. {  
  3. public virtual void displayBrand()  
  4. {  
  5. Console.WriteLine("Base Class - I am Cars");  
  6. }  
Derived Class
  1. public class Maruti : cars  
  2. {  
  3. public override void displayBrand()  
  4. {  
  5. Console.WriteLine("Derived Class - I am Maruti");  
  6. }  
Method overriding can happen in a derived class. That only means that this feature can be used whenever we have a requirement for the method with the same name and signature but a different implementation in the derived class.

Sample Code
  1. namespace MethodOverriding  
  2. {  
  3. class Program  
  4. {  
  5. public class cars  
  6. {  
  7. public virtual void displayBrand()  
  8. {  
  9. Console.WriteLine("Base Class - I am Cars");  
  10. }  
  11. }  
  12.   
  13. public class Maruti : cars  
  14. {  
  15. public override void displayBrand()  
  16. {  
  17. Console.WriteLine("Derived Class - I am Maruti");  
  18. }  
  19. }  
  20. static void Main(string[] args)  
  21. {  
  22. cars car = new Maruti();  
  23. car.displayBrand();  
  24.   
  25. Console.ReadLine();  
  26. }  
  27.   
Method Hiding
Method hiding is nothing but invoking the hidden base class method when the base class variable reference is pointing to the derived class object.
This can be done by the new keyword in the derived class method implementation, in other words the derived class has the same method with the same name and signature.

Base Class

  1. public class cars  
  2. {  
  3. public virtual void displayBrand()  
  4. {  
  5. Console.WriteLine("Base Class - I am Cars");  
  6. }  
Derived Class
  1. public class Honda : cars  
  2. {  
  3. public new void displayBrand()  
  4. {  
  5. Console.WriteLine("Derived Class - I am Honda");  
  6. }  
Here we can see the base class and derived class with the same displayBrand() method name and signature. So whenever a base class variable is pointing to a derived class and the method is called in a normal scenario, it will decide the method call from the derived class at runtime.

But the new keyword will help to invoke the base class version of the method displayBrand(); this is called method hiding.
  1. cars car = new Maruti();  
  2. car.displayBrand(); 
Sample Code
  1. namespace MethodHiding  
  2.   
  3. {  
  4. class Program  
  5. {  
  6. public class cars  
  7. {  
  8. public virtual void displayBrand()  
  9. {  
  10. Console.WriteLine("Base Class - I am Cars");  
  11. }  
  12. }  
  13.   
  14. public class Honda : cars  
  15. {  
  16. public new void displayBrand()  
  17. {  
  18. Console.WriteLine("Derived Class - I am Honda");  
  19. }  
  20. }  
  21.   
  22. static void Main(string[] args)  
  23. {  
  24. cars car = new Maruti();  
  25. car.displayBrand();  
  26.   
  27. Console.ReadLine();  
  28. }  
Important Sticky
  • In method overloading, the method with the name and signature but different return type will provide a complier error and is not allowed in C#.
  • Method overriding is only possible in derived classes.
  • To override a base class method in a derived class with the same name and signature, the base class method should be virtual or abstract.
  •  Method hiding will be done using the new keyword in the derived class for virtual methods in the base class.

No comments:

Post a Comment