Monday, March 25, 2013

Abstract Class vs Interface

Conceptually, abstract classes are very similar to interfaces with a few differences.  One way to think of the two is like this:  An abstract class can be defined as "Is a".  An interface can be defined as "Can do".

When you create an abstract class you are creating a thing that something else would be.  For example, "car" could be an abstract class and everything that inherits from it is a car.  When you create an interface you are defining what something can do.  If you define an interface of "drive", anything that implements that is saying that their object can drive.  The interface doesn't say how to drive it just says your object needs to be able to drive and it defines what things something can do to be able to drive, just not how they do it.

Interfaces cannot implement method implementations.  They can contain abstract methods.

An abstract method defines a method signature (types of parameters it takes and the type it returns), but does not define the implementation or how the method does what it does.  The implementation will be coded in the class that uses the interface.  Many classes can use an interface and each of them may implement a certain method of the interface entirely different.

Interfaces do not have constructors or destructors (special methods that fire upon creation or disposal of an object to allow the class to initialize things or clean up things)

A class can implement multiple interfaces.

An interface is sometimes called a contract or promise.

An interface cannot extend classes, but they can extend other interfaces.

Interfaces can be used as bridges across classes inherited from different base classes. They can also be used to make it easier for third parties to communicate with your classes. 

Abstract Class
Abstract classes must contain at least one abstract method.  Abstract classes can also contain concrete methods or methods that already have an implementation defined.

Just like any other class abstract classes contain constructors and destructors.

A class can not inherit from multiple classes, not even multiple abstract classes.

Abstract classes cannot be instantiated directly.  They must be inherited from and then the class that inherits from them can be implemented.  The abstract keyword indicates that the class is defined for inheritance. 

To create an abstract class you use the abstract keyword:

public abstract class MyAbstractClass {}

Abstract classes can use interfaces, but every class that inherits from the abstract class will be bound by the interface, which means they must implement every method and property in the interface.

An abstract class is used for creating a class hierarchy. 

No comments: