Abstract Classes in C#

CsharpServer Side ProgrammingProgramming

An abstract class in C# includes abstract and non-abstract methods. A class is declared abstract to be an abstract class. You cannot instantiate an abstract class.

Let us see an example, wherein we have 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 Bus derived class −

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

Example

Let us see the complete 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 06:42:55
Advertisements