I was wondering when I should use interfaces.
Lets think about the following:
public abstract class Vehicle { abstract float getSpeed(); }
and :
public interface IVehicle { float getSpeed(); }
I can easily implement both of them, they have the same functionality... BUT I also can add some variables to my vehicle class, which probably should be used in an vehicle (maxSpeed, carType...)
What is the reason to use interfaces?
Thanks!
EDIT: I found a nice link about it in another thread: http://www.thecoldsun.com/en/content/01-2009/abstract-classes-and-interfaces
Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes. If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
An interface is better than a abstract class when you want multiple classes to implement that interface and when you don't have to inherit default behavior.
The main advantages of interface over abstract class is to overcome the occurrence of diamond problem and achieve multiple inheritance. In java there is no solution provided for diamond problem using classes. For this reason multiple inheritance is block using classes in java.
From Java How to Program about abstract classes:
Because they’re used only as superclasses in inheritance hierarchies, we refer to them as abstract superclasses. These classes cannot be used to instantiate objects, because abstract classes are incomplete. Subclasses must declare the “missing pieces” to become “concrete” classes, from which you can instantiate objects. Otherwise, these subclasses, too, will be abstract.
To answer your question "What is the reason to use interfaces?":
An abstract class’s purpose is to provide an appropriate superclass from which other classes can inherit and thus share a common design.
As opposed to an interface:
An interface describes a set of methods that can be called on an object, but does not provide concrete implementations for all the methods... Once a class implements an interface, all objects of that class have an is-a relationship with the interface type, and all objects of the class are guaranteed to provide the functionality described by the interface. This is true of all subclasses of that class as well.
So, to answer your question "I was wondering when I should use interfaces", I think you should use interfaces when you want a full implementation and use abstract classes when you want partial pieces for your design (for reusability)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With