Chitika

Saturday, October 27, 2012

Abstract Class vs Interface


Basically abstract class is an abstract view of any real word entity and interface is more abstract one.
One of the most frequent question in an interview for a Junior/Graduate Developer role is ‘What is the difference between Abstract class and Interface? I have to admit that (as a Graduate).
I thought my intrepidness or whatever that skill I thought I had was far more important than being able to answer the difference between abstract and interface.

                   Abstract Class
Interface
An abstract class can have non-abstract Methods(concrete methods)
In Interface all the methods have to be abstract.
 can declare or use any variables
interface is not allowed to declare variables
In abstract class you can provide default behavior of a function, so that even if child class does not provide its own behavior, you do have a default behavior to work with. Eg. Abstract classes of framework, even if you don’t provide your own behavior, they have a default behavior
You cannot provide a default behavior in interfaces. Interfaces only allow you to provide signature of the method.

You can provide access modifiers to methods in abstract classes.
You cannot provide access modifiers methods in Interfaces.

the aim: making sure something is *eventually* implemented.
the aim: making sure something is interchangeable.
abstract class can have constructor declaration
interface cannot do so
abstract Class is allowed to have all access modifiers for all of its member declaration
Interface we can not declare any access modifier (including public) as all the members of interface are implicitly public.  
we cannot achieve multiple inheritance
Using an Interface we can achieve multiple inheritance.
Can be static , virtual ,abstract or sealed
Interface member cannot be defined using the keyword static, virtual, abstract or sealed
IS-A relationship
CAN-DO relationship.
e.g. Student IS A Person, Employee IS A Person.
e.g. Student CAN enrol, Student CAN submit assignment.
Ex: abstract class AbstractClass
{
    public AbstractClass ()
    {
    }
    int count = 0;
    int Max = 100;
    public abstract void getClassName();
}
Ex:

interface MyInteface
{
    void Method1();
    string Method2();
}


No comments:

Post a Comment