Here are three concepts related to extending the functionality of classes. They are all compile-time concepts, i.e. they have to be implemented in the code as classes are defined.
Inheritance
Inheritance is one of the fundamental concepts in Object Oriented Programming. It enables code reuse by allowing classes to inherit common code from a base or parent class. Inheritance establishes a parent-child (is-a
) relationship, where the child class inherits properties and methods from the parent class (e.g., a Cat
is an Animal
).
While inheritance is powerful, inheritance hierarchies can become complex, especially when dealing with multiple inheritance. Often, there is a need to support multiple inheritance to represent the problem domain and the technical aspects which can lead to the Diamond problem (two parent classes having the same method). To address this issue, many languages do not support multiple inheritance and provide the concept of interfaces to enable additional is-a
relationships (for instance, a Dog
class may have is-a
relationship with Animal
as well as Serializable
etc.)
Mixin
Mixin provides a mechanism for sharing functionality across classes without creating is-a
relationships. They offer a way to reduce the complexity of inheritance hierarchies by allowing classes to include behaviour from multiple sources.
The implementation details of mixins can vary across programming languages, but they generally enable the composition of behaviours from multiple sources into a single class.
Extension Method
Extension methods is a technique to add methods to a class without modifying its definition. They provide syntactic sugar that allows methods to be invoked using object dot notation, improving readability and expressiveness in an OOP context.
Different parts of the code can have access to different extension methods based on what’s relevant.
For example, in .NET, LINQ functionality is implemented through extension methods, enabling powerful query capabilities on collections without modifying their original definitions.