When the following code is executed, an exception java.lang.StackOverflowError is thrown.
main() method in a class Something:
class Something {
public static void main(String args[]) {
System.out.println(Color.RED);
System.out.println(Color.GREEN);
System.out.println(new Color().BLUE);
}
}
Here is the class Color:
class Color {
public static final Color RED = new Color();
public static final Color GREEN = new Color();
public final Color BLUE = new Color();
}
But when I put static behind final in public final Color BLUE = new Color();, the program runs correctly without throwing StackOverflowError. Why does not it throw the Exception? Is it that when JVM identifies that some static object is referring to itself then it should stop? How does Java handle this?
>Solution :
Without the static:
class Color {
public final Color BLUE = new Color();
}
To create an instance of Color (via new Color()), you have to create an instance of Color for the BLUE field; to create that instance of Color, you have to create an instance of Color for the BLUE field; to create that instance of Color, you have to create an instance of Color for the BLUE field, etc. See the problem?
If you make it static:
class Color {
public static final Color BLUE = new Color();
}
You aren’t reinitializing BLUE every time you create a new instance of Color. An instance of Color is created when the class is initialized, and that’s that.