Q: What is one of the primary benefits of encapsulation in OOP?
-
A
It allows data to be accessed globally.
-
B
It hides the internal state of an object from the outside.
-
C
It increases the complexity of the program.
-
D
It decreases code reusability.
B
Answer:
B
Explanation:
Encapsulation is a fundamental concept in object-oriented programming that refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object's components. The primary benefit of encapsulation is that it helps to protect the internal state of an object from unintended or harmful changes. This protection is achieved by making the fields in a class private and providing access to them via public methods, commonly known as getters and setters. This way, the internal implementation of an object can be changed without affecting the external code that uses the object. Encapsulation improves maintainability, flexibility, and reusability of code. It also enhances data integrity and security by preventing external entities from directly manipulating the object's state in unpredictable ways.
Related Topic:
Share Above MCQ