Back to questions
JuniorTheoryCommon
What does the program print?
public class Main {
public static void main(String[] args) {
Counter a = new Counter();
new Counter();
System.out.println(Counter.count + " " + a.id);
}
}
class Counter {
static int count;
int id;
Counter() { id = ++count; }
}2 1
- Expecting
1 1: astaticfield is one for the whole class, so eachnewadds to the samecount, and it reaches 2. - Expecting
2 2:id = ++countcopies the current value into the object once; later changes ofcountdo not reacha.id.
- Why can a static method read
countbut notid? - What happens to this program if
countis declared withoutstatic?