Search code examples
javascopeglobalglobalizationassign

How to change attribute value globally in Java?


I am asking the user to input a value and then I am assigning the same to an attribute but, I want that change to be global. I searched on internet but yet I am not able to find the working solution for it. By the way I m using Java.

Thanx in advance.....



Solution

  • This question has already been extensively covered. If you are looking on how to make a variable global/accessible from outside a class, check here.

    However, if you are looking to make a global variable that can be accessed in and ONLY in a class, you can use the private static Keyword. Here is an example:

    class myClass {
    
        private static int myGlobalVariable;     //Can only be accessed from methods in myClass
    
        void changeMyVariable (int value) {
            // Data validation here if needed
            this.myGlobalVariable = value;
        }
    }