Could someone please explain to me the differences between abstract classes, interfaces, and mixins? I\'ve used each before in
Since many of guys have explained about the definitions and usage, I would like to highlight only important points
Interface:
has a" capabilities.Abstract class:
Share code among several closely related classes. It establishes "is a" relation.
Share common state among related classes ( state can be modified in concrete classes)
I am closing the difference with a small example.
Animal can be an abstract class. Cat and Dog, extending this abstract class establishes "is a" relation.
Cat is a Animal
Dog is a Animal.
Dog can implement Bark interface. Then Dog has a capability of Barking.
Cat can implement Hunt interface. Then Cat has a capability of Hunting.
Man, who is not Animal, can implement Hunt interface. Then Man has a capability of Hunting.
Man and Animal (Cat/Dog) are unrelated. But Hunt interface can provide same capability to unrelated entities.
Mixin:
abstract class and interface. Especially useful when you want to force a new contract on many unrelated classes where some of them have to re-define new behaviour and some of them should stick to common implementation. Add common implementation in Mixin and allow other classes to re-define the contract methods if needed If I want to declare an abstract class, I will follow one of these two approaches.
Move all abstract methods to interface and my abstract class implements that interface.
interface IHunt{
public void doHunting();
}
abstract class Animal implements IHunt{
}
class Cat extends Animal{
public void doHunting(){}
}
Related SE question :
What is the difference between an interface and abstract class?