why i m getting w. getA() as 200 if static attributes belong to class then the outcome must be something else. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

why i m getting w. getA() as 200 if static attributes belong to class then the outcome must be something else.

public class West { public static void main(String[]args) { Zen w = new Zen(223); Zen b = new Zen(); System.out.println(w.getA()); } } public class Zen { private static int a; Zen() { this.setA(200); } Zen(int y) { this.setA(y); } public void setA(int x) { this.a=x; } public static int getA() { return a; } }

28th Mar 2017, 12:35 PM
shobhit
shobhit - avatar
2 Answers
+ 16
Static fields are same for all objects, so the last value of a has been assigned for both w and b. When you assigned a of w as 223, all zen objects' a became 223. Later assigning a of b as 200 (default value), all zen objects' a became 200. This is how static fields work, all objects share the same value.
28th Mar 2017, 1:46 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 8
1st line sets "a" to 223. 2nd line sets "a" to 200. As "a" is a static variable, 200 is printed.
28th Mar 2017, 1:45 PM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar