gpt4 book ai didi

Java - 外部变量声明

转载 作者:行者123 更新时间:2023-12-01 18:21:30 24 4
gpt4 key购买 nike

对于下面的示例,我想知道脚本中私有(private)变量何时被实例化...

class Foo {
private String foo123;

Foo(String s){
foo123 = s;
}
}

public class FooDo {
public static void main(String[] args){
Foo a = new Foo("hello");
}
}

私有(private)String foo123何时首次实例化?

最佳答案

创建新实例时,String foo123 首先被初始化为默认值null。然后,当构造函数执行时,参数s的值被赋值给foo123

更多详情请参阅:JLS 12.5. Creation of New Class Instances

Whenever a new class instance is created, memory space is allocated for it with room for all the instance variables declared in the class type and all the instance variables declared in each superclass of the class type, including all the instance variables that may be hidden (§8.3).

If there is not sufficient space available to allocate memory for the object, then creation of the class instance completes abruptly with an OutOfMemoryError. Otherwise, all the instance variables in the new object, including those declared in superclasses, are initialized to their default values (§4.12.5).

Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object...

关于Java - 外部变量声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27634599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com