Java, Programming Tutorial

Java Tutorial – Difference between interfaces and abstract classes?

Basic differences can be counted as follows:

  • An interface cannot implement any methods, whereas an abstract class can

  • A class can implement many interfaces but can have only one superclass (abstract or not)

  • An interface is not part of the class hierarchy. Unrelated classes can implement the same interface

You should remember that : “When you can fully describe the concept in terms of “what it does” without needing to specify any of “how it does“, then you should use an interface.  If you need to include some implementation details, then you will need to represent your concept in an abstract class.”

Also, if i talk differently : Are there many classes that can be “grouped together” and described by one noun? If so, have an abstract class by the name of this noun, and inherit the classes from it. For example Cat and Dog can both inherit from abstract class Animal, and this abstract base class will implement a method void Breathe() which all animals will thus do in exactly the same fashion.

What kinds of verbs can be applied to my class, that might in general also be applied to others? Create an interface for each of these verbs. For example, All animals can be fed, so I will create an interface called IFeedable and have Animal implement that. Only Dog and Horse are nice enough though to implement ILikeable, but some are not.

As said by someone: the main difference is where you want your implementation. By creating an interface, you can move your implementation to any class that implements your interface. By creating an abstract class, you can share implementation for all derived classes in one central place, and avoid lots of bad things like code duplication.

From howtodoinjava


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s