是否为Java中未使用的字段分配了内存? [英] Is memory allocated for unused fields in Java?
问题描述
我想知道内存分配在Java中如何工作.
I'm wondering how the memory allocation works in Java.
我有一个带有两个实例变量int size
和String name
的class Duck
.这些变量被初始化.如果我不实例化此类,这些变量的内存是否会在运行时在堆上分配?
I have a class Duck
with two instance variables int size
and String 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?
谢谢, 基因
推荐答案
几种可能的情况:
-
如果您不使用课程,则 该类本身未加载到 根本没有类加载器.
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.
这篇关于是否为Java中未使用的字段分配了内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!