abstract keyword in C#

CsharpServer Side ProgrammingProgramming

The abstract keyword in C# is used for abstract classes. An abstract class in C# includes abstract and nonabstract methods. You cannot instantiate an abstract class.

Example of an abstract class Vehicle and abstract method display() −

public abstract class Vehicle {
   public abstract void display();
}

The abstract class has derived classes: Bus, Car, and Motorcycle. The following is an implementation of the Car derived class −

public class Car : Vehicle {
   public override void display() {
      Console.WriteLine("Car");
   }
}

Example

The following is an example of abstract classes in C# −

Live Demo

using System;
public abstract class Vehicle {
   public abstract void display();
}
public class Bus : Vehicle {
   public override void display() {
      Console.WriteLine("Bus");
   }
}
public class Car : Vehicle {
   public override void display() {
      Console.WriteLine("Car");
   }
}
public class Motorcycle : Vehicle {
   public override void display() {
      Console.WriteLine("Motorcycle");
   }
}
public class MyClass {
   public static void Main() {
      Vehicle v;
      v = new Bus();
      v.display();
      v = new Car();
      v.display();
      v = new Motorcycle();
      v.display();
   }
}

Output

Bus
Car
Motorcycle
raja
Published on 24-Jul-2018 11:29:03
Advertisements