1-Java成员初始化顺序

2019-11-03  本文已影响0人  hs_jianshu

1.定义一个简单实体Dog

public class Dog {

    private String name;

    public Dog(String name) {
        System.out.println("Dog Constructor...,dog's name: " + name);
        this.name = name;
    }

    public String getname() {
        return name;
    }

    public void setname(String name) {
        this.name = name;
    }

    public void print() {
        System.out.println("dog's name is: " + name);
    }
}

2.定义测试类InitSeqParent

public class InitSeqParent {

    static Dog a = new Dog("A");

    Dog b = new Dog("B");

    static Dog c;

    static {
        c = new Dog("C");
    }

    Dog d;

    {
        d = new Dog("D");
    }

    InitSeqParent() {
        System.out.println("InitSeqParent Constructor...");
    }

}

3.定义InitSeqParent子类InitSeqChild

public class InitSeqChild extends InitSeqParent {

    static Dog a = new Dog("E");

    Dog b = new Dog("F");

    static Dog c ;

    static {
        c = new Dog("G");
    }

    Dog d ;

    {
        d = new Dog("H");
    }

    InitSeqChild(){
        System.out.println("InitSeqChild Constructor...");
    }

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

4.查看打印结果

Dog Constructor...,dog's name: A

Dog Constructor...,dog's name: C

Dog Constructor...,dog's name: E

Dog Constructor...,dog's name: G

Dog Constructor...,dog's name: B

Dog Constructor...,dog's name: D

InitSeqParent Constructor...

Dog Constructor...,dog's name: F

Dog Constructor...,dog's name: H

InitSeqChild Constructor...

4.结论

上一篇下一篇

猜你喜欢

热点阅读