1

I understand the technical difference between the two, but I don't understand why one is better to use than the others? Can anyone give me an example that would help me distinguish an advantage one has over the other?

For example: If I was making an rpg game, and I was working on some healing items. What would the uml diagram look like. Would I be using an interface for items, and then healing items or abstract classes.

  • Use Interface when u r project manager, and Abstract class when u r team leader :) – gifpif Dec 17 '14 at 07:15
  • I don't know real difference. But one important thing is any class can extends only one class but it can implements more interfaces. So based on requirement it should be decide. – herr Dec 17 '14 at 07:16
  • I'm sorry, are you saying that interfaces should be basically the top of an hierarchy, such as character? Then sub classes will be abstract such as Enemy or Player? – Jack Student MHS Dec 17 '14 at 07:22
  • This can be helpful for you too. http://stackoverflow.com/q/8531292/1055241 – gprathour Dec 17 '14 at 09:22

1 Answers1

1

When to use interfaces

Interfaces are basically used to inherit the behaviour, as we know interfaces can only have abstract methods. When a class implements that interfaces it has to implement all its abstract methods (unless the class itself is an Abstract class), thus it behaves according to the way interfaces defines.

For example, if you want your class to behave as a Thread. You need to implement Runnable interface and override its run() method.

  1. We need to inherit behaviour of two or more forms.
  2. Interfaces are basically created when we know what to do, but we don't know how to do it. To explain in simpler terms I would say, suppose there are 5 tasks which you know must be done. But there can be different ways to do them. Any class implementing them can do them in any way they wish to. So create an interface and put your methods in them.

When to use Abstract class

We know abstract classes can have both abstract as well as concrete methods.

So same example, if you have 5 tasks to be done but for one task there is one default way to do, so you will wish to define its body and you won't be able to do so in interfaces.

In this case we'll create an abstract class. Put 4 abstract methods and one concrete method, which will be inherited by its child classes directly and they won't need to define it on their own. However if they wish they can override its functionality.

Also keep in mind, a class can extend only one abstract class at a time.

gprathour
  • 13,193
  • 5
  • 56
  • 85