What is the Difference Between an Abstract Class and an Interface?

by admin on June 26, 2008

If you spend any time learning to program in an object oriented programming language, like C++, Java, Python or Ruby, you’re going to run across these two concepts. But what is the difference between an abstract class and an interface?

As you probably know, a class acts like a blueprint. It gives you the design from which objects can then be created. But an abstract class is a special kind of class that can’t be instantiated; you can’t make objects from it. The only way you can use an abstract class is to inherit a sub-class from it. And by creating your classes so they inherit from an abstract class, you enforce standards.

For example, let’s say that you create an abstract class to define geometric shapes. You know they’re going to have names, colors, and textures. You can’t make any objects from this, but you can inherit a class that lets you make squares. It has to have name, color and texture, and then any other characteristics you give specifically to the class. You could also create a circle sub-class with the same base characteristics and then custom attributes just for circles.

An interface, on the other hand, isn’t a class at all. It only has signatures for the various methods in the class, but no implementation at all. It allows one class to access the abilities of an object without having any inside knowledge on how it works. One class could ask an object to sort itself, and not care whether it’s made of letters, numbers, or words. If you know an object implements an interface, it will be able to do the task, whether it’s sorting itself, or painting to the screen.

A class can implement multiple interfaces, but it can only inherit from a single abstract class. An abstract class can provide method signatures, as well as default implementation for each method, while an interface can only have the method signatures.

You use abstract classes when you have a hierarchy of classes that you want to share common attributes, sort of like a family tree. You use an interface when you want various implementations to share method signatures.

Leave a Comment

Previous post:

Next post: