What does this code output?
No fair, running it!

  1. public class Hmm {
  2.     public static class X{
  3.         int x = -1;
  4.         public X(){}
  5.         public X(int x ){setX(x);}
  6.         public int getX(){return x;}
  7.         public void setX(int x){this.x = x;}
  8.     }
  9.    
  10.     // the default object has a default value of 0.
  11.     public final static X DEFAULT_X = new X(0);
  12.    
  13.     private X m_X = new X();
  14.    
  15.     // A Hmm object uses the default value
  16.     public Hmm(){
  17.         m_X = DEFAULT_X;
  18.     }
  19.    
  20.     public X getX(){
  21.         return m_X;
  22.     }
  23.    
  24.     public void setX(X x){
  25.         this.m_X.setX(x.getX());
  26.     }
  27.    
  28.     public static void main(String[] args){
  29.         Hmm hmm1 = new Hmm();
  30.         hmm1.getX().setX(15);
  31.        
  32.         Hmm hmm2 = new Hmm();
  33.        
  34.         System.out.println("Hmm1 X = " +
  35.                 hmm1.getX().getX());
  36.         System.out.println("Hmm2 X = " +
  37.                 hmm2.getX().getX());
  38.         System.out.println("DEFAULT_X X = " +
  39.                 DEFAULT_X.getX());
  40.     }
  41. }

Hint: It outputs exactly what the code tells it to! Not much of a hint... It doesn't do what the person wrote it expects it to do though.

Answer: 15 for all three.

Why: Cause the Hmm constructor sets its X reference to the static default object. Thereby the call to set the hmm1 object's X value to 15 actually sets the default value to 15!

Hence, Final Static Objects are the devil!