Why Global variables are not allowed in java?


Forum Post 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.

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.

- rahulkeshar.career June 25, 2014 | Flag |






Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More