简体   繁体   English

是否为Java中的未使用字段分配了内存?

[英]Is memory allocated for unused fields in Java?

I'm wondering how the memory allocation works in Java. 我想知道Java中的内存分配是如何工作的。

I have a class Duck with two instance variables int size and String name . 我有一个class Duck有两个实例变量int sizeString name These variables are initialised. 这些变量已初始化。 Does the memory for these variables get allocated on the heap during run time, if I'm not instantiating this class? 如果我没有实例化这个类,那么这些变量的内存是否在运行时在堆上分配?

Thanks, Gene 谢谢,基因

Several possible scenarios: 几种可能的情况:

  • If you are not using a class, then the class itself is not loaded in a class loader at all. 如果您没有使用类,那么类本身根本不会加载到类加载器中。

  • If you are using a class, but not instantiating it, then instance variables are not occupying memory since there is no instance to begin with. 如果您正在使用类,但没有实例化它,那么实例变量不占用内存,因为没有实例可以开始。

  • If you are using a class, and using an object which is instance of that class, then instance variables are using up memory for each instance, regardless of whether you use these values or not. 如果您正在使用类,并使用作为该类实例的对象,则实例变量会为每个实例使用内存,无论您是否使用这些值。

如果你没有引用类,所有类的Duck甚至都没有通过类加载器加载,所以答案是否定的。

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

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