[英]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中初始化块和构造函数的执行顺序
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.