Posts

Showing posts from July, 2010

Java Object Initialization Order - Know your JLS!

Recently I came across an interesting problem whose solution eluded me at first glance. Consider these three classes:
package com.ds.test; public class Upper { String upperString; public Upper() { Initializer.initialize(this); } } package com.ds.test; public class Lower extends Upper { String lowerString = null; public Lower() { super(); System.out.println("Upper: " + upperString); System.out.println("Lower: " + lowerString); } public static void main(final String[] args) { new Lower(); } } package com.ds.test; public class Initializer { static void initialize(final Upper anUpper) { if (anUpper instanceof Lower) { Lower lower = (Lower) anUpper; lower.lowerString = "lowerInited"; } anUpper.upperString = "upperInited"; } } What output is to be expected from running the Lower class?