What is the output of the following code?
import rope.*; //from ww w. j a v a 2s .c o m import static rope.Main.*; public class MainSwing { private static Main rope1 = new Main(); private static Main rope2 = new Main(); { System.out.println(rope1.length); } public static void main(String[] args) { rope1.length = 2; rope2.length = 8; System.out.println(rope1.length); } } package rope; public class Main { public static int length = 0; }
D.
There are two details to notice in this code.
First, note that MainSwing
has an instance initializer and not a static initializer.
Since MainSwing
is never constructed, the instance initializer does not run.
The other detail is that length is static.
Changes from one object update this common static variable.