How different are interface and abstract class in .Net?
Sapna Malik
//Abstarct Class
public abstract class Vehicles
{
private int noOfWheel;
private string color;
public abstract string Engine
get;
set;
}
public abstract void Accelerator();
//Interface
public interface Vehicles
string Engine
void Accelerator();
More Details : Abstract
Theoretically there are basically 5 differences between Abstract Class and Interface, which are listed as below: -
interface TestInterface
int x = 4; // Filed Declaration in Interface
void getMethod();
string getName();
abstract class TestAbstractClass
int i = 4;
int k = 3;
public abstract void getClassName();
}It will generate a compile time error as :-Error 1 Interfaces cannot contain fields .So we need to omit Field Declaration in order to compile the code properly.interface TestInterface{ void getMethod(); string getName();}
}Above code compiles properly as no field declaration is there in Interface.
// Constructor Declaration
public TestInterface()
public TestAbstractClass()
Above code will generate a compile time error as :-Error 1 Interfaces cannot contain constructors So we need to omit constructor declaration from interface in order to compile our code .Following code compiles s perfectly: -
public interface TestInterface
Above code compiles perfectly.It is not allowed to give any access specifier to the members of the Interface.
public void getMethod();
public string getName();
}Above code will generate a compile time error as :-Error 1 The modifier 'public' is not valid for this item.But the best way of declaring Interface will be to avoid access specifier on interface as well as members of interface.interface Test