In: Computer Science
Which of the following options would be the worst violator of the principle of encapsulation?
A) Global variables
B) Local Variables
C) Public variables
D) Array variables
Can you also explain why the answer wouldn't be global variables, if A is not the correct answer?
Correct Answer: A
Explanation:
Encapsulation is a process through which we bind the data and code in a single unit.
This is the main feature of the Object-Oriented Programming concept. The private data members are hidden from the outside and can be accessed through methods only.
Because of encapsulation, a class has total control over the data stored in fields.
A global variable can be read or modified by any function or method or statement in the program. It is quickly difficult to know the global state in each instance. So, a global variable is the worst violator of the principle of encapsulation.
A local variable is a variable that is declared within a subroutine or block and it can be used inside that block only in which it is declared. This variable exists until the block is executed and after that, it is destroyed automatically. So, it doesn't violate the encapsulation.
In the same way, a public variable can be used in the same class and the inherited class only.
So, option A is the correct option.