Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit properties and behaviors from another class. It enables code reuse and promotes the creation of hierarchical relationships between classes.
Inheritance is based on the principle of "is-a" relationship, where a derived class (also known as a subclass or child class) inherits the characteristics of a base class (also known as a superclass or parent class). The derived class can access and use the members (fields, properties, methods) of the base class, and it can also add its own unique members or override the inherited ones.
Let's consider an example to understand inheritance better. Suppose we have a base class called Animal, which represents generic characteristics of animals. It has properties like Name and Age, and methods like Eat() and Sleep().
public class Animal
{
public string Name { get; set; }
public int Age { get; set; }
public void Eat()
{
Console.WriteLine("The animal is eating.");
}
public void Sleep()
{
Console.WriteLine("The animal is sleeping.");
}
}
Now, let's create a derived class called Dog, which inherits from the Animal class. The Dog class can access the properties and methods of the Animal class, and it can also define its own specific behavior.
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("The dog is barking.");
}
}
In this example, the Dog class inherits the Name and Age properties, as well as the Eat() and Sleep() methods from the Animal class. Additionally, it introduces a new method called Bark(), which is specific to dogs.
Now, we can create an instance of the Dog class and use its inherited and unique members:
Dog dog = new Dog();
dog.Name = "Max";
dog.Age = 3;
dog.Eat(); // Output: The animal is eating.
dog.Sleep(); // Output: The animal is sleeping.
dog.Bark(); // Output: The dog is barking.
As you can see, the Dog class inherits the properties and methods of the Animal class, allowing us to reuse code and define specific behavior for dogs.
In conclusion, inheritance is a powerful mechanism in OOP that facilitates code reuse and promotes the creation of hierarchical relationships between classes. It allows derived classes to inherit and extend the properties and behaviors of base classes, resulting in more organized and maintainable code.
Types of Inheritance in C#
Let's explore each type with examples:
3.1 Single Inheritance: Single inheritance refers to the scenario where a class inherits from only one base class. This is the most common type of inheritance. Here's an example:
public class Animal
{
public void Eat()
{
Console.WriteLine("Animal is eating.");
}
}
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Dog is barking.");
}
}
In this example, the Dog class inherits from the Animal class using single inheritance. The Dog class can access the Eat() method from the Animal class and also has its own Bark() method.
3.2 Multiple Inheritance (not supported in C#): Multiple inheritance refers to the scenario where a class can inherit from multiple base classes. However, C# does not support multiple inheritance directly. Instead, C# provides an alternative called interface inheritance.
3.3 Multilevel Inheritance: Multilevel inheritance refers to the scenario where a derived class inherits from another derived class. Here's an example:
public class Vehicle
{
public void Start()
{
Console.WriteLine("Vehicle is starting.");
}
}
public class Car : Vehicle
{
public void Drive()
{
Console.WriteLine("Car is driving.");
}
}
public class Sedan : Car
{
public void Park()
{
Console.WriteLine("Sedan is parking.");
}
}
In this example, the Car class inherits from the Vehicle class, and the Sedan class inherits from the Car class. The Sedan class can access the Start() method from the Vehicle class, the Drive() method from the Car class, and also has its own Park() method.
3.4 Hierarchical Inheritance: Hierarchical inheritance refers to the scenario where multiple derived classes inherit from a single base class. Here's an example:
public class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape.");
}
}
public class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle.");
}
}
public class Rectangle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a rectangle.");
}
}
In this example, both the Circle and Rectangle classes inherit from the Shape class. Each derived class overrides the Draw() method to provide its own implementation.
These are the main types of inheritance in C#. Each type serves a different purpose and allows you to create class hierarchies that promote code reuse and maintainability. Understanding these types of inheritance is crucial for effective object-oriented programming in C#.
4- Polymorphism : Polymorphism is a fundamental concept in object-oriented programming that allows objects of different types to be treated as objects of a common base type. It enables code reusability, flexibility, and extensibility in software development. In C#, there are several types of polymorphism, each serving a specific purpose. Let's explore them one by one, along with examples:
4.1 Compile-time Polymorphism (Method Overloading): Compile-time polymorphism, also known as method overloading, allows multiple methods with the same name but different parameters to coexist in a class. The compiler determines which method to invoke based on the number, type, and order of the arguments passed. Here's an example
class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
public int Add(int a, int b, int c)
{
return a + b + c;
}
}
// Usage
Calculator calculator = new Calculator();
int result1 = calculator.Add(2, 3); // Invokes the first Add method
int result2 = calculator.Add(2, 3, 4); // Invokes the second Add method
4.2 Runtime Polymorphism (Method Overriding): Runtime polymorphism, also known as method overriding, occurs when a derived class provides its own implementation of a method defined in the base class. The method in the derived class must have the same name, return type, and parameters as the base class method. Here's an example:
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
// Usage
Shape shape = new Circle();
shape.Draw(); // Invokes the Draw method of the Circle class
4.3 Polymorphism through Interfaces: Polymorphism can also be achieved through interfaces. An interface defines a contract that classes can implement, allowing objects of different classes to be treated interchangeably. Here's an example:
interface IShape
{
void Draw();
}
class Circle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
class Rectangle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a rectangle");
}
}
// Usage
IShape shape1 = new Circle();
shape1.Draw(); // Invokes the Draw method of the Circle class
IShape shape2 = new Rectangle();
shape2.Draw(); // Invokes the Draw method of the Rectangle class
4.4 Polymorphism through Abstract Classes: Abstract classes can also be used to achieve polymorphism. An abstract class cannot be instantiated but can be used as a base for derived classes. The derived classes must provide their own implementation of the abstract methods defined in the base class. Here's an example:
abstract class Animal
{
public abstract void MakeSound();
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Woof!");
}
}
class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("Meow!");
}
}
// Usage
Animal animal1 = new Dog();
animal1.MakeSound(); // Invokes the MakeSound method of the Dog class
Animal animal2 = new Cat();
animal2.MakeSound(); // Invokes the MakeSound method of the Cat class
5. Encapsulation :
Encapsulation is one of the fundamental principles of object-oriented programming (OOP) that allows us to bundle data and methods together within a class. It helps in achieving data hiding and abstraction, ensuring that the internal implementation details of a class are hidden from the outside world. In C#, there are three types of encapsulation: public, private, and protected.
5.1 Public Encapsulation: When a member (field, property, or method) is declared as public, it can be accessed from anywhere, both within and outside the class. This type of encapsulation provides the highest level of accessibility. Here's an example:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}
In the above example, the Name and Age properties are declared as public, allowing them to be accessed and modified from any part of the program. The DisplayInfo method is also public, which can be called to display the person's information.
5.2 Private Encapsulation: When a member is declared as private, it can only be accessed within the same class. It is not accessible from outside the class. Private encapsulation provides a higher level of data protection and encapsulation. Here's an example:
public class BankAccount
{
private decimal balance;
public void Deposit(decimal amount)
{
balance += amount;
}
public void Withdraw(decimal amount)
{
if (amount <= balance)
{
balance -= amount;
}
else
{
Console.WriteLine("Insufficient balance.");
}
}
}
In the above example, the balance field is declared as private, ensuring that it can only be accessed and modified within the BankAccount class. The Deposit and Withdraw methods are public, allowing external code to interact with the class while maintaining control over the balance.
5.3 Protected Encapsulation: When a member is declared as protected, it can be accessed within the same class and its derived classes. It is not accessible from outside the class hierarchy. Protected encapsulation provides a level of accessibility between public and private. Here's an example:
public class Animal
{
protected string sound;
public void MakeSound()
{
Console.WriteLine(sound);
}
}
public class Dog : Animal
{
public Dog()
{
sound = "Woof!";
}
}
In the above example, the sound field is declared as protected in the Animal class. It can be accessed and modified within the Animal class and its derived classes, such as the Dog class. The MakeSound method is public, allowing any code to invoke it and hear the sound of the animal.
These are the three types of encapsulation in C# - public, private, and protected. Each type provides a different level of accessibility and encapsulation, allowing developers to control the visibility and usage of class members based on their requirements.
Remember, encapsulation is an essential concept in OOP as it promotes code reusability, maintainability, and security by hiding the internal implementation details of a class.
Thanks for reading , if you have any query, then you can drop a message.
Surya Prakash (Admin) Reply
thanks Jordon