2

I have been reading about Python-Mixin and come to know that it adds some features (methods) to class. Similarly, Java-Interfaces also provide methods to class.

Only difference, I could see is that Java-interfaces are abstract methods and Python-Mixin carry implementation.

Any other differences ?

Adil Malik
  • 8,410
  • 10
  • 53
  • 83
  • 1
    for starters: mixins carry **implementation**. An interface only describes, well, an interface. – Willem Van Onsem Feb 09 '17 at 17:34
  • @WillemVanOnsem yes. But overall purpose is same as both add a specific functionality to some class. right ? – Adil Malik Feb 09 '17 at 17:38
  • Not based on what I've read on mixins. Mixins for instance are popular to patch code whereas interfaces obviously cannot patch code. – Willem Van Onsem Feb 09 '17 at 17:39
  • Some reading: http://stackoverflow.com/questions/533631/what-is-a-mixin-and-why-are-they-useful?rq=1 –  Feb 09 '17 at 17:42
  • @WillemVanOnsem So it means they both different purpose and we can't compare them – Adil Malik Feb 09 '17 at 17:44
  • For the record : starting with java 8 interfaces can implement methods, too. But they shall not be used in a mixin like way; according to the people who gave them to us. – GhostCat Feb 09 '17 at 17:45
  • 2
    Well of course the use is not something strict so it is debatable. But in my opinion mixins can *add* functionality whereas an interface *defines* functionality. – Willem Van Onsem Feb 09 '17 at 17:45
  • @WillemVanOnsem Got your point. Now what to do with this question. – Adil Malik Feb 09 '17 at 17:50

1 Answers1

9

Well, the 'abstract methods' part is quite important.

Java is strongly typed. By specifying the interfaces in the type definition, you use them to construct the signature of the new type. After the type definition, you have promised that this new type (or some sub-class) will eventually implement all the functions that were defined in the various interfaces you specified.

Therefore, an interface DOES NOT really add any methods to a class, since it doesn't provide a method implementation. It just adds to the signature/promise of the class.

Python, however, is not strongly typed. The 'signature' of the type doesn't really matter, since it simply checks at run time whether the method you wish to call is actually present.

Therefore, in Python the mixin is indeed about adding methods and functionality to a class. It is not at all concerned with the type signature.

In summary:

  • Java Interfaces -> Functions are NOT added, signature IS extended.
  • Python mixins -> Functions ARE added, signature doesn't matter.
jbrendel
  • 2,320
  • 3
  • 17
  • 17