-2

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


crazzi
  • 11
  • 1
  • 2
    You should be less vague. What is that attribute? Where is it defined? How is that class used and how instantiated? Do you know what `static` means? (if no, then search for it) – Tom Jan 19 '16 at 22:36
  • 1
    And btw, note that `static` fields have disadvantages, too. One of the big ones is that they make testing harder, since it's easy for a test to change a value from what other tests expect. – yshavit Jan 19 '16 at 22:44
  • let the attribute be of any data type, int , double and so. Yes I do know about static. I need to take an input by a function and without using return i want to use that value outside its scope. – crazzi Jan 20 '16 at 13:40

2 Answers2

1

Java has class members for that. Also known as static fields.

toKrause
  • 512
  • 1
  • 4
  • 13
0

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;
    }
}
Community
  • 1
  • 1
Oscar Anthony
  • 190
  • 3
  • 18
  • ok so the keyword "this" will be used!!!!!!! thanks oscar... I m new to Programming and to learn via coding... – crazzi Jan 20 '16 at 13:47
  • 1
    You are welcome! I am glad I helped you. As you are learing (like me) feel free to post your WORKING code on the [Code Review Stack Exchange](http://www.codereview.stackexchange.com/) website for full peer review. As another member told me, just keep in mind that Code Review is a place where **working** code is reviewed and not a place to ask _how to make it work_, but rather _how to make it work_ **better**. – Oscar Anthony Jan 20 '16 at 15:29