+ 6

static in java, can you explain with example, please?

why we need to use static

12th Jul 2017, 10:00 PM
Assylbek
Assylbek - avatar
3 odpowiedzi
+ 8
I think this small example is nice for the start. https://code.sololearn.com/cFRYbiG5fd6K/?ref=app (and for "why we need to use static?" there are some answers that are not short enough to write everything, but for one example remember "Math-methods"? We can use them without creating any objects of class Math. You can make a counter that will show you infirmation about how many objects were created from your class. You can have a variable/field that is " common"/same for all objects of the class. Same for methods. And so on...)
13th Jul 2017, 1:45 PM
Andrew Harchenko (Tomsk)
Andrew Harchenko (Tomsk) - avatar
+ 5
static tells the compiler that there will only ever be one instance of that object, and any references to it will be to the same one. if you have an object that handles all information for part of your project, static ensures that it uses the same information. for example, say you had a class that held an array for all user information. static ensures that any references to that object will reference the same array.
12th Jul 2017, 10:21 PM
Andrew Lampert
Andrew Lampert - avatar
0
static means you can use it without an instance of the class (the Math methods are a good example).
14th Jul 2017, 7:18 PM
marit vandijk