简体   繁体   中英

Is memory allocated for unused fields in Java?

I'm wondering how the memory allocation works in Java.

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?

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甚至都没有通过类加载器加载,所以答案是否定的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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