Inheritance And Polymorphism In C# Complete Guide
Understanding the Core Concepts of Inheritance and Polymorphism in C#
Inheritance and Polymorphism in C# - A Comprehensive Overview
Inheritance and Polymorphism are fundamental principles in Object-Oriented Programming (OOP) that enable code reusability and flexibility. They form the backbone of creating a hierarchical class structure which allows easy extension and maintenance of applications.
Inheritance in C#
Definition: Inheritance allows a class (derived or child class) to inherit the properties, methods, and other characteristics of another class (base or parent class). This promotes reusability by allowing developers to build upon existing code.
Syntax:
public class BaseClass {
public void BaseMethod() {
Console.WriteLine("Base Method");
}
}
public class DerivedClass : BaseClass {
// DerivedClass inherits from BaseClass
public void DerivedMethod() {
Console.WriteLine("Derived Method");
}
}
Key Concepts:
protected
: Members marked withprotected
are accessible only within the class and its derived classes.
Multiple Inheritance: C# does not support multiple inheritance where a class can inherit from more than one class directly. However, interfaces can be implemented by more than one class indirectly achieving a similar effect.
Polymorphism in C#
Definition: Polymorphism means the ability to take many forms. In the context of OOP, it enables objects to be treated as instances of their parent class yet behave like instances of their actual class.
Types of Polymorphism:
Compile-Time Polymorphism (Static Polymorphism): Achieved through method overloading where multiple methods have the same name but differ in their parameters signature.
public class MathOperations { public int Add(int a, int b) { return a + b; } public double Add(double a, double b) { return a + b; } }
Run-Time Polymorphism (Dynamic Polymorphism): Achieved through method overriding where a derived class provides a specific implementation of a method that is already defined in its base class.
public class Animal { public virtual void Sound() { Console.WriteLine("Animal makes a sound"); } } public class Dog : Animal { public override void Sound() { Console.WriteLine("Dog barks"); } } // Usage Animal myAnimal = new Animal(); // Call the base class method Animal myDog = new Dog(); // Call the derived class method myAnimal.Sound(); myDog.Sound();
Key Concepts:
virtual
: Specifies that a method can be overridden in a derived class.override
: Specifies that the method overrides an abstract or virtual method from a base class.base
: Used to call a method from the base class within its overridden version in the derived class.
Important Facts and Tips:
- Inheritance facilitates code reuse by allowing derived classes to extend and refine the functionality of existing base classes.
- Polymorphism enhances flexibility by enabling objects to be treated uniformly through a common interface, even when their implementations differ.
- The
abstract
keyword is used to define abstract classes that cannot be instantiated directly and must be inherited. Abstract methods can only exist in abstract classes and must be overridden in derived classes. - Interfaces can also be used to achieve polymorphism in C# by defining a contract for what derived classes should implement without specifying how they implement the functionality.
- The
sealed
keyword can be used to prevent a class from being inherited or a method from being overridden. - The
is
keyword checks if an object is of a particular type or its derived type. - The
as
operator attempts to cast an object to a specific type and returnsnull
if the cast is not possible. - Covariance and contravariance in generics allow for more flexible method parameter types.
Online Code run
Step-by-Step Guide: How to Implement Inheritance and Polymorphism in C#
Inheritance Example
Step 1: Understand Basic Inheritance
In C#, inheritance allows a class to inherit fields and methods from another class. The class inheriting is called a derived or child class, and the class being inherited from is called a base or parent class.
Step 2: Define Base Class
Let's start by defining a base class Animal
which will have some common properties and methods:
public class Animal
{
public string Name { get; set; }
public int Age { get; set; }
public void Eat()
{
Console.WriteLine($"{Name} is eating.");
}
public void Sleep()
{
Console.WriteLine($"{Name} is sleeping.");
}
}
Here, the Animal
class has two properties (Name
and Age
) and two methods (Eat
and Sleep
).
Step 3: Define Derived Class
Next, we define a derived class Dog
which inherits from the Animal
class:
public class Dog : Animal
{
public string Breed { get; set; }
public void Bark()
{
Console.WriteLine($"{Name} the {Breed} dog is barking.");
}
}
The Dog
class inherits the Name
and Age
properties, as well as the Eat
and Sleep
methods from the Animal
class. It also has an additional property Breed
and a method Bark
.
Step 4: Use Inheritance in a Program
Let's create a simple program to demonstrate using our Animal
and Dog
classes.
using System;
class Program
{
static void Main()
{
// Creating an instance of Animal
Animal myAnimal = new Animal();
myAnimal.Name = "Generic Animal";
myAnimal.Age = 5;
myAnimal.Eat(); // Output: Generic Animal is eating.
myAnimal.Sleep(); // Output: Generic Animal is sleeping.
// Creating an instance of Dog
Dog myDog = new Dog();
myDog.Name = "Buddy";
myDog.Age = 3;
myDog.Breed = "Golden Retriever";
myDog.Eat(); // Inherited method, Output: Buddy is eating.
myDog.Sleep(); // Inherited method, Output: Buddy is sleeping.
myDog.Bark(); // Dog-specific method, Output: Buddy the Golden Retriever dog is barking.
// Using Dog object as an Animal
Animal myAnimalDog = myDog; // Upcasting
myAnimalDog.Eat(); // Output: Buddy is eating.
myAnimalDog.Sleep(); // Output: Buddy is sleeping.
// Cannot call myAnimalDog.Bark(); because myAnimalDog is treated as an Animal
}
}
Polymorphism Example
Polymorphism means many shapes or forms. In C#, it allows us to perform a single action in different ways. We can achieve polymorphism through method overriding and method overloading.
Method Overriding Example
Step 1: Understand Method Overriding
Method overriding allows a derived class to provide a specific implementation of a virtual method defined in its base class.
Step 2: Define Virtual Methods
First, modify the Animal
class to make Eat
and Sleep
methods virtual:
public class Animal
{
public string Name { get; set; }
public int Age { get; set; }
public virtual void Eat()
{
Console.WriteLine($"{Name} is eating.");
}
public virtual void Sleep()
{
Console.WriteLine($"{Name} is sleeping.");
}
}
Step 3: Override Methods in Derived Class
Now, override these methods in the Dog
class:
public class Dog : Animal
{
public string Breed { get; set; }
public override void Eat()
{
Console.WriteLine($"{Name} the {Breed} dog is eating dog food.");
}
public override void Sleep()
{
Console.WriteLine($"{Name} the {Breed} dog is sleeping in its crate.");
}
public void Bark()
{
Console.WriteLine($"{Name} the {Breed} dog is barking.");
}
}
Step 4: Demonstrate Method Overriding
Update the Main
method to show how polymorphism works with method overriding:
using System;
class Program
{
static void Main()
{
Animal myAnimal = new Animal();
myAnimal.Name = "Generic Animal";
myAnimal.Age = 5;
myAnimal.Eat(); // Output: Generic Animal is eating.
myAnimal.Sleep(); // Output: Generic Animal is sleeping.
Animal myDog = new Dog(); // Upcasting
myDog.Name = "Buddy";
myDog.Age = 3;
((Dog)myDog).Breed = "Golden Retriever"; // Downcasting to access Dog-specific properties
myDog.Eat(); // Overridden method, Output: Buddy the Golden Retriever dog is eating dog food.
myDog.Sleep(); // Overridden method, Output: Buddy the Golden Retriever dog is sleeping in its crate.
((Dog)myDog).Bark(); // Downcasting required to call Dog-specific method, Output: Buddy the Golden Retriever dog is barking.
Dog myRealDog = new Dog();
myRealDog.Name = "Max";
myRealDog.Breed = "Poodle";
myRealDog.Eat(); // Output: Max the Poodle dog is eating dog food.
myRealDog.Sleep(); // Output: Max the Poodle dog is sleeping in its crate.
myRealDog.Bark(); // Output: Max the Poodle dog is barking.
}
}
Method Overloading Example
Step 1: Understand Method Overloading
Method overloading allows multiple methods to have the same name but different parameters.
Step 2: Introduce Method Overloading in Animal
Class
Add overloaded methods in the Animal
class:
public class Animal
{
public string Name { get; set; }
public int Age { get; set; }
public virtual void Eat()
{
Console.WriteLine($"{Name} is eating.");
}
public virtual void Eat(string foodType)
{
Console.WriteLine($"{Name} is eating {foodType}.");
}
public virtual void Sleep()
{
Console.WriteLine($"{Name} is sleeping.");
}
}
Step 3: Override and Overload Methods in Dog
Class
Override the methods in the Dog
class and add method overloading as well:
public class Dog : Animal
{
public string Breed { get; set; }
public override void Eat()
{
Console.WriteLine($"{Name} the {Breed} dog is eating dog food.");
}
public override void Eat(string foodType)
{
Console.WriteLine($"{Name} the {Breed} dog is eating {foodType}.");
}
public override void Sleep()
{
Console.WriteLine($"{Name} the {Breed} dog is sleeping in its crate.");
}
public void Bark()
{
Console.WriteLine($"{Name} the {Breed} dog is barking.");
}
}
Step 4: Demonstrate Method Overloading
Update the Main
method to demonstrate method overloading:
Top 10 Interview Questions & Answers on Inheritance and Polymorphism in C#
Top 10 Questions and Answers on Inheritance and Polymorphism in C#
Answer: Inheritance in C# allows a class to inherit properties, methods, and other members from another class. This promotes reusability and establishes a relationship between classes where the derived class inherits or extends the functionality of the base class.
public class Animal {
public void Eat() {
Console.WriteLine("Animal eats");
}
}
public class Dog : Animal {
// Dog class has access to Animal's 'Eat' method without writing it again
}
2. Can you explain Polymorphism in C#?
Answer: Polymorphism in C# means that a method can behave differently based on the object it is acting upon. There are two types of polymorphism: compile-time (method overloading) and runtime (method overriding).
// Method Overloading - Compile Time Polymorphism
public class Calculator {
public int Add(int a, int b) {return a + b;}
public double Add(double a, double b) {return a + b;}
}
// Method Overriding - Runtime Polymorphism
public class Animal {
public virtual void Speak() {
Console.WriteLine("Animal speaks");
}
}
public class Dog : Animal {
public override void Speak() {
Console.WriteLine("Dog barks");
}
}
3. What are the key benefits of inheritance?
Answer: The key benefits of inheritance include:
- Reusability: Code can be reused across multiple classes without copying code.
- Maintainability: Makes code more organized, which is easier to maintain and update.
- Extensibility: New classes can be added easily with existing functionalities.
- Clarity: Simplifies understanding complex structures by modeling them hierarchically.
4. What is the difference between public
and protected
access modifiers in the context of inheritance?
Answer: Public members are accessible by any class while protected members are only accessible within their defining class and by derived classes. Protected ensures that the member can be used in the derived class but remains hidden to the outside world.
public class Vehicle {
public string Make; // Accessible everywhere
protected string Model; // Accessible within Vehicle and its derived classes
}
5. What is method hiding in C#?
Answer: Method hiding occurs when a derived class declares a new method with the same signature and return type as a method in the base class, using the new
keyword. This hides the base class method in the derived class.
public class Vehicle {
public void Start() {
Console.WriteLine("Vehicle started...");
}
}
public class Car : Vehicle {
public new void Start() {
Console.WriteLine("Car started with a key...");
}
}
6. How does C# handle multiple inheritance?
Answer: C# does not support multiple direct class inheritance to avoid ambiguity and complexity. However, a C# class can implement multiple interfaces which effectively provides multiple inheritance of behavior (signatures without implementation).
interface IFlyable {
void Fly();
}
interface ISwimable {
void Swim();
}
public class Duck : IFlyable, ISwimable { // Multiple interface inheritance
public void Fly() { ... }
public void Swim() { ... }
}
7. What is the purpose of the base
keyword in C#?
Answer: The base
keyword in C# is used to explicitly call methods and access properties from the base class. It’s often used in constructors and overridden methods to ensure proper initialization or to extend base behavior.
public class Vehicle {
public virtual void Start() {
Console.WriteLine("Engine started...");
}
}
public class Car : Vehicle {
public override void Start() {
base.Start(); // Call base class's Start method
Console.WriteLine("Car-specific start logic...");
}
}
8. How do you prevent a class from being inherited in C#?
Answer: You can prevent a class from being inherited by using the sealed
keyword. When applied to a class, deriving from it results in a compile-time error.
public sealed class Singleton {
private static Singleton _instance;
public static Singleton Instance => _instance ?? (_instance = new Singleton());
private Singleton() {}
}
9. What is the concept of a virtual and an abstract method in C#?
Answer: Virtual methods can be overridden in derived classes if needed; they provide a default implementation in the base class.
Abstract methods, however, have no implementation and must be overridden in a non-abstract derived class. A class containing one or more abstract methods must itself be marked as abstract.
public abstract class Animal {
public abstract void Speak(); // Abstract method
public virtual void Eat() { // Virtual method
Console.WriteLine("Animal eats");
}
}
10. Can you explain late binding in C# and how it relates to polymorphism?
Login to post a comment.