- 2

Why we are using static?

12th Mar 2017, 4:35 PM
Harish Singh
Harish Singh - avatar
1 Odpowiedź
+ 3
The reference of a static object is shared throughout the class rather than being an instance of the class. For example: public class test{ public static void main(String[] args){ newClass example = new newClass(5); newClass example2 = new newClass(6); } } class newClass{ public int anInt; newClass(int newint){ anInt = newint; } } Because the public int anInt is not static, when I create multiple objects each of them have their own value. However if it WERE to be static, All objects would have the same value of the variable anInt. So anInt would be 6 if anInt was a static int, however had it not be static: example1.anInt would be 5, and example2.anInt would be 6. Hopefully that made sense, you will need to understand OOP for this. Fyi you cannot call something that's non-static from something that is static- because static does not belong to the instance of the class. So you can use a static variable if you want everything of that class to share the same variable reference. The main class must be static in order for the compiler to access the class without creating an instance of the class.
12th Mar 2017, 8:32 PM
Rrestoring faith
Rrestoring faith - avatar