When we call an abstract method of a abstract class from its constructor it returns null. Why?
abstract class OverloadStaticMethod {
OverloadStaticMethod(){
doSubStuff();
}
abstract void doSubStuff();
public static void main(String args[]) {
new ParentClass();
}
}
public class ParentClass extends OverloadStaticMethod {
String s = "Hello world";
void doSubStuff() {
System.out.println(s);
}
}
Output:
null
Image a field that is defined like this:
That should make clear that the initializing expression used for a field is just code, and code needs to be executed at some point.
"Hello World"
seems like a constant expression, but it doesn't count here (there are rules; in particular, you'd have to make s static and final for it to count as a constant).The simple explanation is that the line of code that assigns
"Hello World"
to variables
has not executed yet, because execution runs in reverse order. When you haveclass GrandParent
,class Parent extends GrandParent
andclass Child extends Parent
, execution is:The general fix is to never call overridable methods in any constructor. If you want 'substuff' as a concept, introduce an
init()
method (generally constructors shouldn't do much except do some validation of parameters and store them, this is one of many reasons for why that is the general style advice), or possibly have the result of substuff be passed in as argument to the constructor of the parent class.NB: Note that 'overload a static method' is an impossibility in java. static methods do not partake in dynamic dispatch at all, and 'overload' as a concept applies to dynamic dispatch. It's like saying you can taste green - it doesn't make sense.