简体   繁体   English

Java中对象的初始化

[英]Initialization of object in Java

I am learning some basic OOP concepts in Java.我正在学习 Java 中的一些基本 OOP 概念。 Consider the following code snippet:考虑以下代码片段:

class my_class{
    int a;
    public my_class() {
    System.out.print(a+" ");
    a = 10;
    System.out.print(a);
    }
}
class Main{
    public static void main(String[] args) {
    my_class my_object = new my_class();
    }
}

The output of the following code is: 0 10以下代码的输出为: 0 10

According to my understanding:根据我的理解:

  1. my_class is the name of the class my_class是类的名称
  2. my_object is the reference of the object I am creating my_object是我正在创建的对象的引用
  3. new operator allocates memory and returns it's address which is stored in my_object new运算符分配内存并返回它的地址,该地址存储在my_object
  4. my_class() is the constructor which initializes the object's fields with default value 0 and later assigns it 10 my_class()是构造函数,它使用默认值 0 初始化对象的字段,然后为其分配 10

Now consider the code:现在考虑代码:

class my_class{
    final int a;
    public my_class() {
    a=10;
    System.out.print(a);
    }
}
class Main{
    public static void main(String[] args) {
    my_class my_object = new my_class();
    }
}

From my previous understanding it should have created my_object with field final int a set to the default value 0 which should be unchangeable and flag an error at a=10;根据我之前的理解,它应该创建my_object字段final int a设置为默认值 0,该值应该是不可更改的,并在a=10;处标记错误a=10; but instead it works and prints the output: 10但它可以工作并打印输出: 10

Where am I going wrong?我哪里错了?

You can initialize any final field once, either in the constructor (that is, each constructor once), or in its declaration.您可以初始化任何final一次场,无论是在构造函数(即,每个构造一次),或在其声明。

(Notably, if you want the arguments to the constructor to play a part in the value of the final variable, you must initialize it in the constructor -- otherwise final variables would be kind of useless!) (值得注意的是,如果您希望构造函数的参数在最终变量的值中起作用,则必须在构造函数中对其进行初始化——否则最终变量将毫无用处!)

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

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