Abstract classes vs. interfaces vs. mixins

后端 未结 7 1409
难免孤独
难免孤独 2021-01-29 20:10

Could someone please explain to me the differences between abstract classes, interfaces, and mixins? I\'ve used each before in

7条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-29 20:33

    Since many of guys have explained about the definitions and usage, I would like to highlight only important points

    Interface:

    1. To define a contract ( preferably stateless - I mean no variables )
    2. To link unrelated classes with "has a" capabilities.
    3. To declare public constant variables (immutable state)

    Abstract class:

    1. Share code among several closely related classes. It establishes "is a" relation.

    2. 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:

    1. If you want a mixture of both 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.

    1. 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?

提交回复
热议问题