Friday, May 12, 2023

Opps Part 1 : Abstraction

  Abstraction in C# is a fundamental concept of object-oriented programming (OOP) that allows developers to create complex systems by breaking them down into simpler and more manageable parts. Abstraction enables the developer to hide the complexities of the system by creating abstract classes, interfaces, and methods, and exposing only the necessary functionalities to the users.

 using System;  
 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!");  
   }  
 }  
 class Program  
 {  
   static void Main(string[] args)  
   {  
     Animal myDog = new Dog();  
     Animal myCat = new Cat();  
     myDog.MakeSound(); // Output: Woof!  
     myCat.MakeSound(); // Output: Meow!  
   }  
 }                              

In this example, we have an abstract class called Animal that contains an abstract method called MakeSound(). The Animal class cannot be instantiated, and any class that derives from it must implement the MakeSound() method.

We then create two classes, Dog and Cat, that inherit from the Animal class and implement the MakeSound() method with their own unique sounds.

Finally, in the Main method, we create objects of the Dog and Cat classes and call their MakeSound() methods, which outputs "Woof!" and "Meow!" respectively.

This is an example of abstraction because we are abstracting away the implementation details of the Animal class, and only exposing the necessary functionality through the MakeSound() method. This allows us to create different types of animals with their own unique sounds, without having to worry about the underlying implementation details.


Abstract Base Class points

There are some important points about Abstract Base Class.

  1. An Abstract Base class cannot be instantiated; it means the object of that class cannot be created.
  2. The class having the abstract keyword with some of its methods (not all) is known as an Abstract Base Class.
  3. The class having the Abstract keyword with all its methods is a pure Abstract Base Class.
  4. The method of the abstract class that has no implementation is known as "operation". It can be defined as an abstract void method ();
  5. An abstract class holds the methods, but the actual implementation is made in the derived class.

No comments:

Post a Comment

Opps Part 1 : Abstraction

  Abstraction in C# is a fundamental concept of object-oriented programming (OOP) that allows developers t...