Also, I read somewhere that interfaces are more efficient than abstract classes. Is this true?
No, neither are more efficient then the other.
Abstraction gives you better inherited behavior changes of class, since you only have to make changes in one place. Where as, interfaces allow you to separate the behavior of a class into multiple descriptions.
This is because a class can only extend one abstract class. So all of the behavior of the abstract class is inherited, where as a class can implement multiple interfaces which allows that class to represent multiple behaviors.
Having an interface is no problem except with the method used to construct subclass objects. Where should this method go now?
Maybe something like this.
interface Animal {
getAnimalobject(parameter);
}
class Dog implements Animal {
function getAnimalobject(parameter) { return .... }
}
class Elephant implements Animal {
function getAnimalobject(parameter) { return .... }
}
Lots of reasons why this is better then abstraction, but I don't want to really write them all down. Here are my top reasons for interfaces over abstraction.
Top Reasons To Use Interface
Abstracted classes can create object and memory management problems. For example; if you create an abstract class called "List" and it had an abstract method called "Remove". When you implement your own "Remove" method, should you delete memory or keep it? You simply don't know what the base class is doing, or what it will do in the future. If someone modifies the base class to handle the list differently, then you could likely break things in your class.
Interfaces are easy to use in testing. Creating mock objects of an interface is far easier then creating a mock object of abstract classes.
Objects can implement multiple interfaces but only one abstract class.
Changes to an abstract class can cause a cascade of failures across multiple classes, or worse just one small hidden failure in a rarely used class.