Java – why initialize a member object after the constructor of a superclass?

I encountered an interesting problem yesterday. Although the repair is very simple, I am still a little vague about its "reason"

I have a class that has a private member variable assigned at instantiation, but if it is used in an abstract function called by the constructor of a superclass, the variable has no value The solution to the problem is very simple. I just declare variables static and assign them correctly Some code to illustrate the problem:

class Foo extends BaseClass
{
    private final String bar = "fooBar!";
    public Foo()
    {
        super();
    }

    @Override 
    public void initialize()
    {
        System.out.println(bar);
    }
}

And base classes:

abstract class BaseClass
{
    public BaseClass()
    {
        initialize();
    }

    public abstract void initialize();
}

In this example, when we call new foo(); It will output (null) instead of the expected foobar!

Since we instantiate an object of type foo, should its members be assigned and assigned before calling its (and its superclass's) constructor? Is this specified in the Java language or is it JVM specific?

Thank you for any comments!

Solution

bar =“fooBar!” Assignment of; Inline into constructor during compilation

The superclass constructor runs the before subclass constructor, so it's natural to execute the statement afterwards

But generally speaking, the overridable method called from the constructor is bad practice

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>