当前位置:网站首页>Subclass a inherits from parent class B, a a = new a(); Then the execution sequence of the constructor of parent class B, the static code block of parent class B, the non static code block of parent c

Subclass a inherits from parent class B, a a = new a(); Then the execution sequence of the constructor of parent class B, the static code block of parent class B, the non static code block of parent c

2022-06-25 11:20:00 User 9854323

(1) Subclass A Inherited parent class B, A a = new A(); be :

Parent class B Static code block -> Subclass A Static code block -> Parent class B Non static code block -> Parent class B Constructors -> Subclass A Non static code block -> Subclass A Constructors

(2) If a subclass constructor explicitly calls a constructor of the parent class , Then call the constructor

class C {
    C() {
        System.out.print("C");
    }
}

class A {
    C c = new C();

    A() {
        this("A");
        System.out.print("A");
    }

    A(String s) {
        System.out.print(s);
    }
}

class Test extends A {
    Test() {
        super("B");
        System.out.print("B");
    }

    public static void main(String[] args) {
        new Test();
    }
}

CBB First new A subclass object , Then you need to call the constructor to initialize the subclass object , But this class inherits from A, So you need to call the constructor of the parent class first , Through here super(“B”) The shown calls the parameterized construct of the parent class . Initialize the objects in the parent class before executing the parameterized construction of the parent class , To the c Members are initialized , Called C Nonparametric construction of class , So the call order is : First call C Nonparametric construction of class Call again A Class with parameters Finally, call the construction of subclasses

(3) stay JVM call mian Method is used to initialize the static content . In sequence : Static variable of parent class , The static code block of the parent class , Static variables of subclasses , Static code block of subclass .

public class Test{
    static int cnt = 6;
    static{
        cnt += 9;
    }
public static void main(string[] args){
    System.out.println(“cnt =” + cnt);
}
static{
    Cnt /=3;
    };
}

Cnt=5

原网站

版权声明
本文为[User 9854323]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251056180203.html