在Java中运行构造函数代码之前,字段是否已初始化? [英] Are fields initialized before constructor code is run in Java?

查看:119
本文介绍了在Java中运行构造函数代码之前,字段是否已初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释下面程序的输出?我认为构造函数在实例变量之前初始化。所以我期望输出是XZYY。

  class X {
Y b = new Y ;

X(){
System.out.print(X);
}
}

class Y {
Y(){
System.out.print(Y);
}
}

public class Z extends X {
Y y = new Y();

Z(){
System.out.print(Z);
}

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


解决方案正确的初始化顺序是:


  1. 静态变量初始化和静态初始化块,如果该类以前没有初始化,则按文本顺序。

  2. 在构造函数中调用super(),无论是显式还是隐式。

  3. 实例变量初始化和实例初始化块, li>
  4. super()之后的构造函数的剩余部分。

//docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.5\">§2.17.5-6Java虚拟机规范。


Can anyone explain the output of following program? I thought constructors are initialized before instance variables. So I was expecting the output to be "XZYY".

class X {
    Y b = new Y();

    X() {
        System.out.print("X");
    }
}

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

public class Z extends X {
    Y y = new Y();

    Z() {
        System.out.print("Z");
    }

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

解决方案

The correct order of initialisation is:

  1. Static variable initialisers and static initialisation blocks, in textual order, if the class hasn't been previously initialised.
  2. The super() call in the constructor, whether explicit or implicit.
  3. Instance variable initialisers and instance initialisation blocks, in textual order.
  4. Remaining body of constructor after super().

See sections §2.17.5-6 of the Java Virtual Machine Specification.

这篇关于在Java中运行构造函数代码之前,字段是否已初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆