为什么以及如何在 Java 中不通过构造函数初始化实例变量?

why and how instance variable get initialized without getting initialized by constructor in Java?

public class Test{
int i;
Test(){
    System.out.println(i);
}
public static void main(String[] args){
    Test obj=new Test();
    }
}

输出=0

P.S: 我在Java 很天真所以这个问题可能很愚蠢。我期待着你的支持。谢谢

Static/Instance 未初始化的字段将被编译器设置为默认值。

下面的table表示数据类型的默认值:

+--------------------------+----------------------------+
|        Data Type         | Default Value (for fields) |
+--------------------------+----------------------------+
| byte                     | 0                          |
| short                    | 0                          |
| int                      | 0                          |
| long                     | 0L                         |
| float                    | 0.0f                       |
| double                   | 0.0d                       |
| char                     | '\u0000'                   |
| String (or any object)   | null                       |
| boolean                  | false                      |
+--------------------------+----------------------------+

更多信息,您可以查看文档here

看,每个 Instance-Variable or Class-Variabledefault value

初始化

In case instance-variable is some Reference type then it will be always assigned with it's default value by null

所以,在你的例子中,int 是原始类型,其 default 值为 0(zero),这就是你在输出中得到 0 的原因。