静态方法内存分配
我们有堆和栈两种分类。当一个对象被创建时,该对象的内存存储在堆中。如果类有静态方法,可以使用类名调用怎么办?如果没有创建对象,那么它将如何分配内存,如果创建了,它将在哪里分配内存?
We have two classifications heap and stack . When a object is created, memory for object is stored in heap. What if the class has static methods ,which can be called using class name. If object is not created then how will it allocate memory and if it does where will it allocate memory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它取决于 JVM,但静态字段通常存储在堆上的特殊对象中。 (您可以在堆转储中看到它)卸载类加载器时,它的类及其静态“对象”/字段也会被清理。
静态“对象”的唯一不同之处是您无法获得对它的引用。 (但是你可以使用反射来访问字段)
It depends on the JVM, but static fields are usually stored in a special object on the heap. (You can see it in a heap dump) When the ClassLoader is unloaded, its classes and their static "objects"/fields are also cleaned up.
The only thing different about the static "object" is you can't get a reference to it. (But you can use reflection to access the fields)
方法(即代码)不存储在对象中;而是存储在对象中。类的所有对象将共享方法的代码。无论使用哪种语言(Java、C++ 或几乎任何其他语言),任何方法(无论是否静态)都只有一个代码副本。通常,有一个特定的内存区域(即 C++ 等本机语言中的 CODE 段,或 Java 中的特殊堆区域)用于加载代码。
Methods (i.e., code) aren't stored in an object; all objects of a class will share the code for a method. Regardless of language (Java, C++, or virtually anything else) there will be only a single copy of the code for any method, static or not. Generally there's a specific area of memory -- i.e., a CODE segment in a native language like C++, or a special heap area in Java -- where code is loaded.
堆的永久代(PermGen)空间包含永久类
元数据和描述符信息。
永久代空间始终保留给类和那些与之相关的类
类(静态成员、静态函数等...)
静态函数属于该类,因此无需调用即可调用它们
创建类的对象。
Permanent Generation(PermGen) space of heap contain permanent class
metadata and descriptors information.
PermGen space always reserved for classes and those that are tied to
the classes(Static members, static functions, etc...)
Static function belongs to the class so they can be called to without
creating the object of the class.