Created
November 15, 2011 21:58
-
-
Save lpar/1368514 to your computer and use it in GitHub Desktop.
Java field initialization weirdness with primitive values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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