Invoking an abstract method in a Java superstructure

Since the subclass has not yet been constructed, is it unsafe to call an abstract method in the constructor of the superclass?

However, if the behavior of the method does not depend on the construction of the subclass, for example. just return the constant regarding the subclass, is it still unsafe or will it work reliably?

In addition, if it works, how to do it if I do not want to abstract from the superclass?

Update: for the last question

public class SuperClass { public SuperClass() { System.out.println(getValue()); } public String getValue() { return "superclass"; } public static void main(String[] args) { new SubClass(); } } class SubClass extends SuperClass { public SubClass() { super(); // Comment out this or not will not affect the result } public String getValue() { return "subclass"; } } 

I wrote a test and found out: the result: subclass Thanks to the @Tim Pote application.

+4
source share
2 answers

Usually (although not necessarily) considered unsafe. As you said, a superclass cannot be completely constructed and, therefore, will not be ready to handle all the calls that a subclass can make in its overridden method.

However, in the case where all subclasses simply return a constant that is independent of any other method, then this should be fine. The only drawback is that you cannot guarantee that the subclass will override this method accordingly.

Regarding your last question: this is not an abstract and concrete superclass problem. This is a problem with calling overridden methods in the constructor. Abstraction against the concrete does not matter.


Edit in response to OP comment

I'm not sure what you mean by "polymorphic." A call to a virtual method always invokes a submaximal implementation. The only time an implementation of superclasses is called is the super keyword. For instance:

 public class SuperClass { public SuperClass() { System.out.println(getValue()); } public String getValue() { return "superclass"; } public static void main(String[] args) { new SubClass(); } public static class SubClass extends SuperClass { public String getValue() { return "subclass"; } } } 

outputs subclass .

And this:

 public class SuperClass { public SuperClass() { System.out.println(getValue()); } public String getValue() { return "superclass"; } public static void main(String[] args) { new SubClass(); } public static class SubClass extends SuperClass { public String getValue() { return super.getValue() + " subclass"; } } } 

prints superclass subclass

+4
source

As others have explained, there is an inherent risk of calling abstract methods in the superclass constructor.

The only exception I found is when the subclass provides some “persistent” information, for example getId() , getHandledMessages() , etc.

+1
source

Source: https://habr.com/ru/post/1446127/


All Articles