Are classes instances? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

Are classes instances?

public class MyClass { public static int k = 0; public static void main(String[ ] args) { k++; MyClass.k++; System.out.println(MyClass.k); // outputs 2 } } In the code snippet above, I created a static variable "k" and i used a uninary operator ++ to add one to the variable. In the same variable, i accessed it via MyClass.k and k directly, but what is the difference?

30th Oct 2017, 10:51 AM
Morgan Lee
Morgan Lee - avatar
3 Antworten
+ 1
Since you have declared this as static so it can be accessed through class and also it is a global variable so it can be accessed directly in any method of the same class. However if this k variable would have been in another class you can only access it through that class. eg public class A{ public static int i =0; } public class B { public static void main(String[] args){ A.i++; // will compile i++; // shows error System.out.println(A.i); } } output : 1
30th Oct 2017, 12:01 PM
Peerzada Burhan
Peerzada Burhan - avatar
+ 1
i don't think there is any difference as far as the memory efficiency is concerned but using k++ is efficient and simple so definitely k++ when you use variable in the same class
30th Oct 2017, 2:05 PM
Peerzada Burhan
Peerzada Burhan - avatar
0
yeah ok, but for best practise, should i run MyClass.k to access the static variable in the same class or should k++ be done instead i understand that from other classes, i would have to use MyClass.k
30th Oct 2017, 12:41 PM
Morgan Lee
Morgan Lee - avatar