Difference between Abstract Class and Interface in C#
An abstract class is a way to achieve the abstraction in C#. An Abstract class is never intended to be instantiated directly. This class must contain at least one abstract method, which is marked by the keyword or modifier abstract in the class definition. The Abstract classes are typically used to define a base class in the class hierarchy. An Interface member cannot contain code bodies. Type definition members are forbidden. Properties are defined in an interface with the help of an access block get and set, which are permitted for the property.
Difference Between An Abstract Class And An Interface
- An Abstract class doesn’t provide full abstraction but an interface does provide full abstraction; i.e. both a declaration and a definition is given in an abstract class but not so in an interface.
- Using Abstract we cannot achieve multiple inheritance but using an Interface we can achieve multiple inheritance.
- We can not declare a member field in an Interface.
- We can not use any access modifier i.e. public, private, protected, internal etc. because within an interface by default everything is public.
- An Interface member cannot be defined using the keyword static, virtual, abstract or sealed.
// C# program to illustrate the // concept of abstract class using System; // abstract class 'Test' public abstract class Test { // abstract method 'harunu()' public abstract void harunu(); } // class 'Test' inherit // in child class 'C1' public class C1 : C { // abstract method 'harunu()' // declare here with // 'override' keyword public override void harunu() { Console.WriteLine("Class name is C1"); } } // class 'Test' inherit in // another child class 'C2' public class C2 : Test { // same as the previous class public override void harunu() { Console.WriteLine("Class name is C2"); } } // Driver Class public class main_method { // Main Method public static void Main() { // 'obj' is object of class // 'Test' class // 'Test' cannot // be instantiate C obj; // instantiate class 'C1' obj = new C1(); // call 'harunu()' of class 'C1' obj.harunu(); // instantiate class 'C2' obj = new C2(); // call 'harunu()' of class 'C2' obj.harunu(); } } // C# program to illustrate the // concept of interface using System; // A simple interface interface harunu{ // method having only declaration // not definition void show(); } // A class that implements the interface. class MyClass : harunu{ // providing the body part of function public void show() { Console.WriteLine("Welcome to Harunu!!!"); } // Main Method public static void Main(String[] args) { // Creating object MyClass objharunu = new MyClass(); // calling method objharunu.show(); } }