Abstraction is an object-oriented programming concept about hiding unnecessary details and only focusing on those details that are necessary. Abstraction helps to reduce the complexity of programming code.
A car is an example of abstraction. You start a car by pressing the start button. You don’t need to know how the engine actually starts. The inner workings of the car are completely hidden from the driver. A car is seen as a car, rather than a sum of parts and functionalities.
We can use abstraction to abstract away the specifics of whether a car is automatic or manual, and just expose the essential functionalities of a car to the program.
Abstraction is also about generalization. With abstraction, we can take one definition of data and make it applicable to different, but somewhat related, types of data. An example is taking Car blueprints and making them applicable to both manual and automatic cars.
Abstraction can be achieved via abstract classes. An abstract class creates a contract for the classes that will implement it. Abstract classes are defined using the
Car can be an abstract class, with methods such as
getCarType(), etc. We can then implement this abstract class using classes such as
AutomaticCar. Each of these classes will need all the functionality that the abstract
Car class provides.
With abstract classes, the program only needs to know about the
Car class and the functions that it provides. The internal implementation details of automatic or manual cars are kept hidden.
Abstraction vs encapsulation
While they seem very similar, encapsulation is about information hiding while abstraction is about providing general features but hiding the implementation details.