Skip to content

Instantly share code, notes, and snippets.

@lpar
Created November 15, 2011 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lpar/1368514 to your computer and use it in GitHub Desktop.
Save lpar/1368514 to your computer and use it in GitHub Desktop.
Java field initialization weirdness with primitive values
public class SubClass extends SuperClass {
protected int myValue = 69;
public SubClass() {
// You might think that field initialization will have been performed before this constructor is executed.
super();
// However, Java doesn't actually perform all the field initialization for this object until this point in the code.
// Note also that there's nothing in the source code to say that initialization happens here.
System.out.println("Subclass constructor continuing");
outputFirstField();
}
public static void main(String[] args) {
SubClass t = new SubClass();
}
}
import java.lang.reflect.Field;
public abstract class SuperClass {
/**
* Output the value of the first field of the object.
*/
public void outputFirstField() {
Field f = this.getClass().getDeclaredFields()[0];
int x = 0;
try {
x = f.getInt(this);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Value of field " + f.getName() + " is " + Integer.toString(x));
}
public SuperClass() {
System.out.println("Superclass constructor called");
outputFirstField();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment