Abstraction in OOPs
Abstraction in Object Oriented Programming helps to hide the irrelevant details of an object. Abstraction is separating the functions and properties that logically can be separated to a separate entity which the main type depends on.
This kind of Abstraction helps in separating the members that change frequently. Abstraction is one of the key principles of the OOAD(Object oriented analysis and Design). Applying Abstraction during the design and domain modeling, helps a lot in design the a system which is flexible and maintainable.
Abstraction is achieved by Composition.
A Car has Engine, wheels and many other parts. When we write all the properties of the Car, Engine, and wheel in a single class, it would look this way:
In the above example, the attributes of wheel and engine are added to the Car type. As per the programming, this will not create any kind of issues. But when it comes to maintenance of the application, this becomes more complex.
Abstraction has three advantages:
- By using abstraction, we can separate the things that can be grouped to another type.
- Frequently changing properties and methods can be grouped to a separate type so that the main type need not under go changes. This adds strength to the OOAD principle -"Code should be open for Extension but closed for Modification".
- Simplifies the representation of the domain models.
Applying the abstraction with composition, the above example can be modified as given below:
You can see that the attributes and methods related to the Engine and Wheel are moved to the respective classes.
Engine and Wheel are referred from the Car type. When ever an instance of Car is created, both Engine and Wheel will be available for the Car and when there are changes to these Types(Engine and Wheel), changes will only be confined to these classes and will not affect the Car class.
Abstraction is one of the fundamental principles of Object Oriented Programming languages.
It helps to reduce the complexity and also improves the maintainability of the system. When combined with the concepts of the Encapsulation and Polymorphism, Abstraction gives more power to the Object oriented programming languages.