+ 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; } }
2 ответов
+ 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.
+ 8
1st line sets "a" to 223. 2nd line sets "a" to 200. As "a" is a static variable, 200 is printed.