简体   繁体   English

Java中实例变量的初始化

[英]Initialization of Instance Variables in Java

How does instance variable id gets initialized to 0 when we have provided our own default constructor and did not initialize id in it?当我们提供了自己的默认构造函数并且没有在其中初始化 id 时,实例变量 id 如何初始化为 0? The output comes to be id:0 status:B How is id 0? output变成了id:0 status:B id 0怎么来的?

`class Demo{
    private int id;
    private char status; 

    public Demo(){ 
    status = 'B';
    }

    public void display(){
    System.out.println("Id:="+id+" Status:"+status);
    }

    public static void main(String args[]){
    Demo ob = new Demo();
    ob.display();
    }
}`

Below are the default intializations 以下是默认初始化

The following chart summarizes the default values for the above data types. 下表总结了上述数据类型的默认值。

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

In Java, every variable not initialized gets automatically initialized to the default value of the type it is declared, ie: 在Java中,每个未初始化的变量都会自动初始化为声明的类型的默认值,即:

  • float: 0.0f 浮点数:0.0f
  • int/short/byte: 0 int / short / byte:0
  • long: 0L 长:0L
  • Object: null 对象:null
  • boolean: false 布尔值:false

Primitive types default to certain values. 基本类型默认为某些值。 For int it's 0. 对于int为0。

TL;DR - Instance variables have default values. TL;DR - 实例变量有默认值。 See [1].见[1]。


You are correct to state that the value is zero, or rather 0. This is because in Java, instance variables, which are variables that reside within a class, but not a method, do not have to be manually initialised.您对 state 的值是零,或者更确切地说是 0 是正确的。这是因为在 Java 中,实例变量是驻留在 class 中的变量,但不是方法,不必手动初始化。

In Java, when declaring instance variable(s), if no value is given, the compiler will apply a default value to allow the program to run.在 Java 中,当声明实例变量时,如果没有给出值,编译器将应用默认值以允许程序运行。 While this can be used in circumstances in which you may desire to change the value of the instance variable later, it is generally considered bad practice.虽然这可以在您可能希望稍后更改实例变量的值的情况下使用,但它通常被认为是不好的做法。

See here, the Java Documentation:请参阅此处,Java 文档:

Default Values默认值

It's not always necessary to assign a value when a field is declared.声明字段时并不总是需要赋值。 Fields that are declared but not initialized will be set to a reasonable default by the compiler.已声明但未初始化的字段将由编译器设置为合理的默认值。 Generally speaking, this default will be zero or null, depending on the data type.一般来说,此默认值将为零或 null,具体取决于数据类型。 Relying on such default values, however, is generally considered bad programming style.然而,依赖于这样的默认值通常被认为是糟糕的编程风格。

For information regarding the default values as per data type, see[1].有关每个数据类型的默认值的信息,请参阅 [1]。

The documentation has further information regarding other variables, namely local:该文档包含有关其他变量的更多信息,即本地:

Local variables are slightly different;局部变量略有不同; the compiler never assigns a default value to an uninitialized local variable.编译器永远不会为未初始化的局部变量分配默认值。 If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it.如果您不能在声明局部变量的地方对其进行初始化,请确保在尝试使用它之前为其分配一个值。 Accessing an uninitialized local variable will result in a compile-time error.访问未初始化的局部变量将导致编译时错误。

The reason for the difference between local, and instance variables (in the way they are treated by the JVM) is namely that the instance variables are loaded into an area of memory known as the 'Heap' [2], and the local variables are loaded into a separate memory area called the 'Stack' [2];局部变量和实例变量之间的差异(在 JVM 处理它们的方式上)的原因是实例变量被加载到称为“堆”[2] 的 memory 区域,而局部变量是加载到一个单独的 memory 区域,称为“堆栈”[2]; although, now, there are exceptions to this [3].尽管现在也有例外 [3]。 The Heap stores objects and references to objects, and as such, Instance Variables are stored with their objects.堆存储对象和对对象的引用,因此,实例变量与其对象一起存储。 Ultimately, there was a choice made, that was rather arbitrary, that forced the initialisation of local, but not instance variables.最终,做出了一个相当随意的选择,它强制初始化局部变量,而不是实例变量。

[1] https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html [1] https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

[2] https://www.guru99.com/java-stack-heap.html [2] https://www.guru99.com/java-stack-heap.html

[3] Why do instance variables have default values in java? [3] 为什么实例变量在java中有默认值?

实例变量使用默认值初始化,整数则为0。

id is a primitive type, int , which defaults to 0 . id是基本类型int ,默认值为0

You're thinking of objects 你在想物体

Which are actually references to objects, and these default at null , meaning they point to no object. 实际上是对对象的引用,它们默认为null ,表示它们不指向任何对象。

  • because the default value of int type is 0 . 因为int类型的默认值为0
  • All instance variables are assigned with default values 所有实例变量都分配有默认值

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

It's not always necessary to assign a value when a field is declared. 声明字段时,不一定总是需要分配值。 Fields that are declared but not initialized will be set to a reasonable default by the compiler. 编译器会将已声明但未初始化的字段设置为合理的默认值。 Generally speaking, this default will be zero or null, depending on the data type. 通常,此默认值将为零或null,具体取决于数据类型。 Relying on such default values, however, is generally considered bad programming style. 但是,通常认为依赖于此类默认值是不好的编程风格。

The following chart summarizes the default values for the above data types. 下表总结了上述数据类型的默认值。

+------------------------+----------------------------+
| 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            |
+------------------------+----------------------------+

"For type int, the default value is zero, that is, 0". “对于int类型,默认值为零,即0”。
You can see the default values in the language specification: http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#96595 您可以在语言规范中看到默认值: http : //docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#96595

As per your code, id is an instance variable and if the instance variables are not defined then it takes up the default value. 根据您的代码,id是一个实例变量,如果未定义实例变量,则它将使用默认值。 In your case as id is int so the value is 0 在您的情况下,由于id为int,因此值为0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM