why static block in child class does not get executed?

前端 未结 5 709
难免孤独
难免孤独 2020-12-19 21:38

here is the code

public class ClassResolution {
static class Parent {
    public static String name;
    static {
        System.out.println(\"this is Parent         


        
5条回答
  •  执念已碎
    2020-12-19 22:28

    In short, Child.name is equal to Parent.name, and the compiler compiles it like so.

    Because name is a static field of the Parent class, it is a class method in Parent, not Child. The Java compiler allows a shortcut where child classes can call static parent class methods/fields as if they come from their own class, but internally they are compiled with regards to the parent class.

    Although your code refers to Child.name, it is internally Parent.name, as handled by the compiler. Then, because the Child class isn't initialized, the static initializer block is never run, and name remains "Parent".

提交回复
热议问题