简体   繁体   English

如果仅在对象初始化期间给定内存,如何初始化类成员变量(实例变量)?

[英]How class member variables(instance variable) can be initialized if the memory is given only during object initialisation?

As we know that a class can have objects which get memory only by new classname(). 我们知道,一个类可以具有仅通过新的classname()获得内存的对象。 Then how it is possible to assign some value to an instance of a class. 然后,如何为类的实例分配一些值。

class Work{
   public int a = 55;
}

class DoStuff{
      public static void main(String[] args){
      Work obj = new Work(); // intialises variable now
      System.out.println(obj.a) // a already has value 55
   }
}

Order of execution of Initialization blocks and constructor in Java Java中初始化块和构造函数的执行顺序

  • Static initialization blocks will run whenever the class is loaded first time in JVM 每当在JVM中首次加载类时,静态初始化块都将运行
  • Initialization blocks run in the same order in which they appear in the program. 初始化块以它们在程序中出现的顺序运行。
  • Instance Initialization blocks are executed whenever the class is initialized and before constructors are invoked. 每当初始化类时,在调用构造函数之前,都会执行实例初始化块。 They are typically placed above the constructors within braces. 它们通常放在大括号内的构造函数上方。

https://www.geeksforgeeks.org/order-execution-initialization-blocks-constructors-java/ https://www.geeksforgeeks.org/order-execution-initialization-blocks-constructors-java/

So in your case public int a = 55; 因此,在您的情况下public int a = 55; is invoked before constructor of Work class. Work类的构造函数之前调用。 JVM first reserves memory for an object and then starts initialization of all object properties. JVM首先为对象保留内存,然后开始初始化所有对象属性。

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

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