Difference between Abstract class and interface
- A class can implement any number of interfaces but a subclass can at most use only one abstract class.
- An abstract class can have non-abstract methods (concrete methods) whereas all methods of interfaces must be abstract.
- An abstract class can declare or use any variables whereas an interface is not allowed to do so.
The following code compiles properly since no field declaration is in the interface.
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:
Error1- Interfaces cannot contain fields.
So we need to omit the Field Declaration to compile the code properly.
interface TestInterface
{
void getMethod();
string getName();
}
abstract class TestAbstractClass
{
int i = 4;
int k = 3;
public abstract void getClassName();
}
- An abstract class can have a constructor declaration whereas an interface cannot.
So the following code will not compile:
interface TestInterface
{
// Constructor Declaration
public TestInterface()
{
}
void getMethod();
string getName();
}
abstract class TestAbstractClass
{
public TestAbstractClass()
{
}
int i = 4;
int k = 3;
public abstract void getClassName();
}
The code above will generate the compile time error:
Error 1-Interfaces cannot contain constructors
So we need to omit the constructor declaration from the interface to compile our code.
The following code compiles perfectly:
interface TestInterface
{
void getMethod();
string getName();
}
abstract class TestAbstractClass
{
public TestAbstractClass()
{
}
int i = 4;
int k = 3;
public abstract void getClassName();
}
- An abstract class is allowed to have all access modifiers for all of its member declarations whereas in an interface we cannot declare any access modifier (including public) since all the members of an interface are implicitly public.
Note: here I am talking about the access specifiers of the member of interfaces and not about the interface.
The following code will explain it better.
It is perfectly legal to provide an access specifier as Public (remember only public is allowed).
public interface TestInterface
{
void getMethod();
string getName();
}
The code above compiles perfectly. - It is not allowed to provide any access specifier to the members of the interface.
interface TestInterface
{
public void getMethod();
public string getName();
}
The code above will generate the compile time error:
Error 1: The modifier 'public' is not valid for this item.
But the best way of declaring an interface will be to avoid access specifiers on interfaces as well as members of interfaces.
interface Test
{
void getMethod();
string getName();
}
Comments
Post a Comment