Crystal-Lang-Mixin

Crystal-Lang-Mixin

When a class can inherit features from more than one parent class, the class is supposed to have multiple inheritance. But Crystal does not support multiple inheritance directly and instead uses a facility called mixin. Mixins in Crystal allows modules to access instance methods of another one using include method. Mixins provides a controlled way of adding functionality to classes. The code in the mixin starts to interact with code in the class. In Crystal, a code wrapped up in a module is called mixins that a class can include or extend. A class consist many mixins.

# Modules consist a method 
module Child_1 
def a1 
puts "This is Child one."
end
end
module Child_2 
def a2 
puts "This is Child two."
end
end
module Child_3 
def a3 
puts "This is Child three."
end
end

# Creating class 
class Parent 
include Child_1 
include Child_2 
include Child_3 
def display 
puts "Three modules have included."
end
end

# Creating object 
object = Parent.new

# Calling methods 
object.display 
object.a1 
object.a2 
object.a3

Output

Three modules have included.

This is Child one.

This is Child two.

This is Child three.
In above example, module Child_1 consist of the method a1 similarly module Child_2 and Child_3 consist of the methods a2 and a3. The class Parent includes modules Child_1, Child_2 and Child_3 . The class Parent also include a method display. As we can see that the class Parent inherits from all three modules. the class Parent shows multiple inheritance or mixin. Object can access all four methods i.e. a1,a2,a3 and display().

source:geeksforgeeks