Tuesday, June 5, 2012

Difference between Abstract Class and Interface:

Most of the people confuses with Abstract class and interface. Here I am planning to share some information with examples, I hope this will help you more………

Simple abstract class looks like this:
public abstract class KarateFight{
public void bowOpponent(){
//implementation for bowing which is common for every participant       }
public void takeStand(){
//implementation which is common for every participant
}
public abstract boolean fight(Opponent op);
//this is abstract because it differs from person to person
}

The basic interface looks like this:
public interface KarateFight{
public boolean fight(Opponent op);
public Integer timeOfFight(String person);
}

The differences between abstract class an interface as fallows:
1.  Abstract class has the constructor, but interface doesn’t.
2.  Abstract classes can have implementations for some of its members (Methods), but the interface can’t have implementation for any of its members.
3.  Abstract classes should have subclasses else that will be useless..
4. Interfaces must have implementations by other classes else that will be useless
5. Only an interface can extend another interface, but any class can extend an abstract class..
6.  All variable in interfaces are final by default
7. Interfaces provide a form of multiple inheritance. A class can extend only one other class.
8. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
9.  A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
10. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.
11. Accessibility modifier(Public/Private/internal) is allowed for abstract class. Interface doesn’t allow accessibility modifier
12.  An abstract class may contain complete or incomplete methods. Interfaces can contain only the signature of a method but no body. Thus an abstract class can implement methods but an interface can not implement methods.
13.  An abstract class can contain fields, constructors, or destructors and implement properties. An interface can not contain fields, constructors, or destructors and it has only the property’s signature but no implementation.
14. Various access modifiers such as abstract, protected, internal, public, virtual, etc. are useful in abstract Classes but not in interfaces.
15.  Abstract scope is upto derived class.
16.  Interface scope is upto any level of its inheritance chain.

No comments:

Post a Comment