Java parent class child class class loading order

Look at the code first, guess the result
public class Base
{
    private String baseName = "base";
    public Base()
    {
        callName();
    }
 
    public void callName()
    {
        System. out. println(baseName);
    }
 
    static class Sub extends Base
    {
        private String baseName = "sub";
        public void callName()
        {
            System. out. println (baseName) ;
        }
    }
    public static void main(String[] args)
    {
        Base b = new Sub();
    }
}

I thought it was "sub" at first, but when I ran it, I got null

analysis:
Base b=new Sub(); Declared as a parent class and implemented as a subclass.
The constructor of the parent class is called first.
The callName() method in the parent class constructor has been rewritten in the subclass, so the subclass callName() method is executed.
The variable baseName in the subclass has not been initialized at this time (because the parent class constructor has not been executed yet), so the output is null.

Attachment: Class loading sequence
(1) Parent class static code block (including static initialization block, static properties, but excluding static methods)
(2) Subclass static code block (including static initialization block, static properties, but excluding static methods ) )
(3) Parent class non-static code block (including non-static initialization block, non-static property)
(4) Parent class constructor
(5) Subclass non-static code block (including non-static initialization block, non-static property)
(6 ) subclass constructor

Reference : https://www.nowcoder.com/questionTerminal/c2bfb1512dfa4a7eab773a5871a52402

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327059649&siteId=291194637