Thursday 11 October 2012

Differences between Abstract class and Interface.

Hi friends, Here I have explained what are the basic differences between Abstract class and Interface. This is the general question always asked in interviews.

There are  5 main differences between abstract class and Interface:-
1.)A class can implement many number of interfaces but a sub class can at most use only one abstract class.
2.) An abstract class can have non-abstract method(Concrete method) while in case of interface all the methods has to abstract.
3.)An abstract class can declare or use any variables while an interface is not allowed to do so.
          So the following code cann't be compiled:-
     interface TestInterface
{
int x=4;
int k=3;
void getMethod();
string getName();
}

abstract class TestAbstract
{
int i=4;
int x=3;
public abstract void getClassName();
}

It will generate a compile time error as:-
Error1 Interface cannot contain fields.

4.)An abstract class have constructor declaration while an interface can not do so.


  interface TestInterface
{
//constructor declaration
public TestInterface()
{

}
void getMethod();
string getName();
}

abstract class TestAbstract
{
public TestAbstract()
{

}
int i=4;
int x=3;
public abstract void getClassName();
}

Above code generate a compile time error as:-
Error1 Interface does not contain constructors.

5.) An abstract class is allowed to have all modifier for all of its member declaration while in interface we cannot declare any access modifier(including public) as all the member of interface are implicitly public.

Correct code:
public Interface TestInterface
{
void getMethod();
string getName();
}

Inccorect Code:

 Interface TestInterface
{
public void getMethod();
public string getName();
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.