In Java, is there any way to initialize a field before the super constructor runs?
Even the ugliest hacks I can come up with are rejected by the compiler:
class Base
{
Base(String someParameter)
{
System.out.println(this);
}
}
class Derived extends Base
{
private final int a;
Derived(String someParameter)
{
super(hack(someParameter, a = getValueFromDataBase()));
}
private static String hack(String returnValue, int ignored)
{
return returnValue;
}
public String toString()
{
return "a has value " + a;
}
}
Note: The issue disappeared when I switched from inheritance to delegation, but I would still like to know.
a
? – Resinoussuper
call. So, the super constructor is always run before the field initialization. – Arria
is only accessible inDerived
, why does it matter that it gets initialised beforesuper()
is called? Initialising it right after does not make a difference in the example your provide (unless you call an overriden method from the Base constructor, which begins to smell quite fishy). – ByproductSystem.out.println(this)
internally callstoString()
, which is overriden to print the value ofa
. – Leggett