What does this code output?
No fair, running it!
-
public class Hmm {
-
public static class X{
-
int x = -1;
-
public X(){}
-
public X(int x ){setX(x);}
-
public int getX(){return x;}
-
public void setX(int x){this.x = x;}
-
}
-
-
// the default object has a default value of 0.
-
public final static X DEFAULT_X = new X(0);
-
-
private X m_X = new X();
-
-
// A Hmm object uses the default value
-
public Hmm(){
-
m_X = DEFAULT_X;
-
}
-
-
public X getX(){
-
return m_X;
-
}
-
-
public void setX(X x){
-
this.m_X.setX(x.getX());
-
}
-
-
Hmm hmm1 = new Hmm();
-
hmm1.getX().setX(15);
-
-
Hmm hmm2 = new Hmm();
-
-
hmm1.getX().getX());
-
hmm2.getX().getX());
-
DEFAULT_X.getX());
-
}
-
}
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!