Static Method Memory Allocation

2020-01-31 07:07发布

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?

3条回答
兄弟一词,经得起流年.
2楼-- · 2020-01-31 07:45
  • 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.

查看更多
做个烂人
3楼-- · 2020-01-31 07:49

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.

查看更多
forever°为你锁心
4楼-- · 2020-01-31 07:54

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)

查看更多
登录 后发表回答