What is the difference between a mixin and inheritance?
mix-in is a specific, restricted case of (multiple) inheritance used for implementation purposes; some languages (e.g. Ruby) support it without supporting generalized multiple inheritance.
Mixins are vastly used in a more "plugin" like manner.
They are the same but in a different context each one of them. Usually when we talk about inheritance we are talking about SINGLE inheritance, and a mixin is a construct that allows MULTIPLE inheritance.
This is a language construct that is highly controversial in the OOP world because of:
But that aside, is a powerful construct that's used in various languages and frameworks, some examples are:
https://github.com/django/django/blob/98126cdfaf632abc8f0b5e65910e46a4eedc4641/django/views/generic/list.py#L194
https://docs.djangoproject.com/en/3.1/topics/class-based-views/mixins/
I think its important to note, that mixin doesn't imply inheritance. According to wikipedia, a Mixin is:
In object-oriented programming languages, a mixin is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depends on the language. Mixins are sometimes described as being "included" rather than "inherited".
Specifically, in a language like perl, mixins can be added using the Exporter module:
package Mixins;
use Exporter qw(import);
our @EXPORT_OK = qw(pity);
# assumes it will be mixed-in to a class with a _who_do_i_pity method
sub pity {
my ($self) = @_;
printf("I pity %s\n", $self->_who_do_i_pity('da foo'));
}
Which can be mixed-in to any module containing one, or more, method(s) at a time:
package MrT
use Mixins qw(pity);
sub new {
return bless({}, shift);
}
sub _who_do_i_pity {
return 'da foo!'
}
Then in your MrT
module can be used thusly:
use MrT;
MrT->new()->pity();
I know its an absurd example, but, it gets the point across...