I am experiencing a seemingly odd problem, although I understand there is probably some reason behind this design, and would like to find out why it is this way.
Consider two classes, Foo and Bar. Bar extends Foo and overrides a method that Foo implements. Foo is quite simple:
public class Foo {
public Foo() {
System.out.println("Foo constructor");
someMethod();
}
public void someMethod() {
System.out.println("Foo.someMethod");
}
}
Bar is where the problem is. It defines an array which is initialized outside the constructor (I don't know what the term is for this). I noticed that when someMethod is called from Foo, the array has not yet been initialized, but when right after the call to super(), the array IS initialized. Here is Bar:
public class Bar extends Foo {
int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
public Bar() {
super();
System.out.println("FooBar constructor");
if (a == null) System.out.println("FooBar a is null");
}
public void someMethod() {
if (a == null) System.out.println("FooBar.someMethod a is null");
}
}
This doesn't quite make sense. I want to access the array from a method which is called in the super constructor, but the array isn't initialized. I have tried to think of a solution. My first idea was to initialize the array in Bar's constructor, but that still won't initialize it before the call to super.
For reference, the output is as follows:
Foo constructor
FooBar.someMethod a is null
FooBar constructor
Why is Java designed like this, and what is the best way around it?