Calling abstract method of a Abstract class

775 Views Asked by At

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
1

There are 1 best solutions below

1
On

Image a field that is defined like this:

public class Example {
    private long mark = System.currentTimeMillis();
}

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 variable s has not executed yet, because execution runs in reverse order. When you have class GrandParent, class Parent extends GrandParent and class Child extends Parent, execution is:

  • First, GrandParent's initializing expressions and initializers.
  • Then, GrandParent's constructor.
  • Then, Parent's initializing expressions and initializers.
  • Then, Parent's constructor.
  • Then, Child's initializing expressions and initializers.
  • Then, Child's constructor.

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.