What is the difference between method overriding and method hiding?
In C#, the concepts of method overriding and method hiding are similar to what I described in my previous response, but they have some specific details related to the C# language and its implementation of inheritance and polymorphism. Let's explore the differences between method overriding and method hiding in the context of C#:
1. Method Overriding in C#:
Method overriding in C# is used to provide a specific implementation for a method in a derived class that has the same name, return type, and parameters as a method in its base class. The 'virtual' keyword is used in the base class to indicate that a method can be overridden, and the override keyword is used in the derived class to indicate that a method is intended to override a 'virtual' method in the base class.
Key points about method overriding in C#:
-
The base class method must be marked as 'virtual', and the derived class method must be marked as 'override'.
- The 'override' keyword ensures that the method in the derived class indeed overrides the base class method.
- Method overriding allows for runtime polymorphism, where the method implementation is determined based on the actual type of the object at runtime.
Example in C#:
class Animal {
public virtual void MakeSound() {
Console.WriteLine("Animal makes a sound");
}
}
class Dog : Animal {
public override void MakeSound() {
Console.WriteLine("Dog barks");
}
}
2. Method Hiding (Method Shadowing) in C#:
Method hiding in C# is achieved by using the 'new' keyword to define a method in a derived class with the same name as a method in the base class. This is similar to method hiding in other languages like Java.
Key points about method hiding in C#:
-
The 'new' keyword is used to hide a method from the base class, and it explicitly indicates that the method in the derived class is intentionally hiding the method in the base class.
- Method hiding is determined at compile-time based on the reference type, not the actual object type.
- Method hiding does not participate in polymorphism.
Example in C#:
class Parent {
public static void StaticMethod() {
Console.WriteLine("Static method in Parent");
}
}
class Child : Parent {
public new static void StaticMethod() {
Console.WriteLine("Static method in Child");
}
}
In C#, method overriding and method hiding behave similarly to other object-oriented languages like Java, with some differences in syntax and keyword usage specific to the C# language.