Probably "Difference Between abstract Class and Interface" is the most frequent question being asked in .Net world . In this tutorial, I will explain the difference theoretically followed by code snippet. 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.
An abstract class can have constructor declaration while an interface can not do so.So following code will not compile :-
// 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 compile s perfectly :-
An abstract Class is allowed to have all access modifiers for all of its member declaration while in interface we can not declare any access modifier(including public) as all the members of interface are implicitly public. Note here I am talking about the access specifiers of the member of interface and not about the interface.Following code will explain it better :-It is perfectly legal to give provide access specifier as Public (Remember only public is allowed) public interface TestInterface { void getMethod(); string getName(); } Above code compiles perfectly.It is not allowed to give any access specifier to the members of the Interface.
public interface TestInterface
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
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: