rahulkeshar.career
BAN USER- 0 Answers Why Global variables are not allowed in java?
I request others to refine the post as and when they find it wrong or out of context.
- rahulkeshar.career June 25, 2014
Imagine a real life scenario. In an office there is a coffee machine, which is accessible to everyone (all people). Now, since it is accessible to everyone so anyone can do anything to the milk in coffee machine (assume that someone added lime juice to milk). In order to prevent this we have to take some measures (like installing a CCTV to keep mischief out). But we are an indefinite specie, and can always find a way to sour the milk, so we can say, its kind of difficult to always keep an eye on the Coffee machine.
Also, there is always an option that we do not provide Coffee machine at all in the office, but if you wish to have a coffee, you can approach a coffee shop (As in case of Java, no global variables are allowed but you can create public class with static variable)
Now, taking this concept to our Java or C++, both are free to either implement or not implement Global variables, but Java chooses not to. Why?
• One, They are difficult to understand (as we have to look at the whole system, in above example we have to keep an eye to the behaviour of each and every person in the office) and maintain (as for the reasons stated in above example)
• Two, One of the features of Object Oriented programming is to keep data and the functions that operate on the data together (basically Encapsulation, to achieve high degree of cohesion), and global variables kind of defeats this.
• Three, they are error-prone (as souring of milk in above example), and are not associated with objects, and are therefore not object-oriented programming.
The only instance where a global value can be safe is where it is used as a constant.| Flag | PURGE
Created a program in Java (In comments I have provided some of the combinations which are being discussed in the comments above):
Output:
- rahulkeshar.career June 20, 2014StudentRanking: 1 Laddo: 1
StudentRanking: 7 Laddo: 2
StudentRanking: 2 Laddo: 1
StudentRanking: 5 Laddo: 2
StudentRanking: 3 Laddo: 1
Total Number of Laddo Teacher has to buy is:7