Recent

6/recent/ticker-posts

Header Ads Widget

C Sharp abstract and its use

abstract keyword (modifier) is used to create abstract class, methods, properties etc. abstract means its a missing or incomplete. we also call hiding a something from or essential information from user. 

The abstract keyword is used for create abstract classes and methods:

class: cannot  create objects (to access it, it must be inherited from another class).

method: only used in an abstract class, and it does not have a body. The body is provided by the derived class i.e inherited class


For real world example:

Driver can drive, but he don't know the process of car's internal process like how to show speed, how to operate break while press on break.




abstract class Car 
{
  public abstract void Model();
  public void NoOfWheel() 
  {
    Console.WriteLine("4");
  }
}

create object of this

Car myCar=new Car();

In this line throw error as "Cannot create an instance of the abstract class or interface 'Animal'"

       
 
       
abstract class Car
{
  // Abstract method (does not have a body)
  public abstract void Model();
  // Regular method
  public void NoOfWheel()
  {
    Console.WriteLine("4");
  }
}

// Derived class (inherit from CAR)
class Tesla : Car
{
  public override void Model()
  {
    // The body of Model() is provided here
    Console.WriteLine("Model No: 234");
  }
}

class Program
{
  static void Main(string[] args)
  {
    Tesla myTesla = new Tesla(); // Create a Tesla object
    myTesla.Model();  // Call the abstract method
    myTesla.NoOfWheel();  // Call the regular method
  }
}
       
 

Post a Comment

0 Comments