简体   繁体   中英

Initialization of object in Java

I am learning some basic OOP concepts in Java. 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

According to my understanding:

  1. my_class is the name of the class
  2. my_object is the reference of the object I am creating
  3. new operator allocates memory and returns it's address which is stored in my_object
  4. my_class() is the constructor which initializes the object's fields with default value 0 and later assigns it 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; but instead it works and prints the output: 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.

(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!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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