Understanding Inheritance & Polymorphism in C#
🔷 What is Inheritance in C#?
Inheritance allows one class (child) to inherit the members (fields, methods) from another class (parent). This promotes code reusability and logical hierarchy.
Example:
// Base class
public class Animal {
public virtual void Speak() {
Console.WriteLine("The animal makes a sound.");
}
}
// Derived class
public class Dog : Animal {
public override void Speak() {
Console.WriteLine("The dog barks.");
}
}
// Usage
class Program {
static void Main() {
Animal a = new Dog();
a.Speak(); // Output: The dog barks.
}
}
🔶 Understanding Polymorphism
Polymorphism lets you use a child class as its parent type. It allows a single method to behave differently based on the object it is acting upon.
🔸 The 'virtual' Keyword
The virtual
keyword in a base class method indicates that the method can be overridden in any derived class.
🔹 The 'override' Keyword
The override
keyword in a derived class is used to modify the behavior of a virtual method defined in the base class.
⚙️ The 'base' Keyword
The base
keyword is used to call methods or constructors from the base class.
Example using base
:
public class Vehicle {
public virtual void Start() {
Console.WriteLine("Vehicle is starting");
}
}
public class Car : Vehicle {
public override void Start() {
base.Start(); // Calling base class method
Console.WriteLine("Car is starting");
}
}
🧩 Abstract Classes in C#
An abstract class in C# serves as a blueprint. It can't be instantiated directly and may contain abstract methods that must be implemented by derived classes.
Example of Abstract Class:
public abstract class Shape {
public abstract double Area();
}
public class Circle : Shape {
private double radius;
public Circle(double r) {
radius = r;
}
public override double Area() {
return Math.PI * radius * radius;
}
}
class Program {
static void Main() {
Shape s = new Circle(5);
Console.WriteLine(s.Area()); // Output: 78.5398...
}
}
🔗 Interfaces in C#
An interface is a contract. It contains no implementation but defines methods that implementing classes must include. It's a core part of polymorphism and abstraction in C#.
Interface Example:
public interface ILogger {
void Log(string message);
}
public class FileLogger : ILogger {
public void Log(string message) {
Console.WriteLine("Logging to file: " + message);
}
}
class Program {
static void Main() {
ILogger logger = new FileLogger();
logger.Log("Application started"); // Output: Logging to file: Application started
}
}
📌 Why Use Virtual, Override, and Base Together?
These three keywords are most powerful when used together. The virtual
keyword defines a method that can be changed, override
changes its behavior in the child class, and base
can be used to include the original behavior.
Combined Example:
public class Person {
public virtual void Introduce() {
Console.WriteLine("Hello, I'm a person.");
}
}
public class Student : Person {
public override void Introduce() {
base.Introduce();
Console.WriteLine("I'm also a student.");
}
}
class Program {
static void Main() {
Person p = new Student();
p.Introduce();
// Output:
// Hello, I'm a person.
// I'm also a student.
}
}
🎯 Multiple Interface Inheritance
C# doesn't support multiple class inheritance, but it does support multiple interface inheritance. This lets a class implement multiple behaviors from different sources.
Example:
public interface IReadable {
void Read();
}
public interface IWritable {
void Write();
}
public class Document : IReadable, IWritable {
public void Read() {
Console.WriteLine("Reading the document.");
}
public void Write() {
Console.WriteLine("Writing to the document.");
}
}
class Program {
static void Main() {
Document doc = new Document();
doc.Read(); // Output: Reading the document.
doc.Write(); // Output: Writing to the document.
}
}
🔍 Method Hiding Using the 'new' Keyword
If a derived class defines a method with the same name as in the base class, you can use the new
keyword to explicitly hide the base class method.
Code Sample:
public class BaseClass {
public void Show() {
Console.WriteLine("BaseClass Show()");
}
}
public class DerivedClass : BaseClass {
public new void Show() {
Console.WriteLine("DerivedClass Show()");
}
}
class Program {
static void Main() {
BaseClass obj = new DerivedClass();
obj.Show(); // Output: BaseClass Show()
}
}
📌 Summary
Mastering the use of virtual
, override
, and base
in C# is key to writing clean, flexible, and powerful object-oriented code. Whether you're working with abstract classes, interfaces, or inheritance hierarchies, these keywords let you control and extend functionality efficiently. Combine them with multiple interfaces and method hiding for truly dynamic applications.
❓ Frequently Asked Questions (FAQs)
1. What’s the difference between override and new in C#?
override
modifies a virtual
method in a derived class. new
hides a base class method without overriding it.
2. Can you inherit from multiple classes in C#?
No, C# supports single class inheritance but allows multiple interfaces to be implemented.
3. What happens if you forget to use override for a virtual method?
If you forget to use override
, the base method is called instead, unless you're hiding the method using new
.
4. Why use abstract classes over interfaces?
Abstract classes allow shared implementation. Interfaces only define contracts with no implementation.
5. How does polymorphism help in real projects?
It allows flexible and maintainable code by enabling objects to be treated as instances of their base class or interface.
Post a Comment