存储在堆栈或堆中的对象方法?

Object methods stored in stack or heap?

堆对象内部的方法会怎样?

所以我一直在阅读堆栈和堆内存管理。

我假设这些方法存储在堆栈中,因为“方法存储在堆栈中”。但我无法找到这方面的确认。例如构造函数会发生什么?

我看到的文章或教程视频只是在主要部分给出了方法示例class。

有人能回答这个问题吗?

将根据 Java 中的工作原理进行解释。

Methods and variables(inside methods) are stored in the stack.

局部变量(方法内部的变量)存储在堆栈中。但不是方法本身。

所谓方法,我们指的是行为或需要执行的指令列表。这不会改变每个方法调用,甚至不会因创建的每个对象实例而改变。 class 级别的行为保持不变。

行为存储在称为方法区的区域中。您可以参考Java Spec了解更多详情。

根据规范,

The method area is created on virtual machine start-up. Although the method area is logically part of the heap, simple implementations may choose not to either garbage collect or compact it. This version of the Java Virtual Machine specification does not mandate the location of the method area or the policies used to manage compiled code.

方法区的位置留给JVM实现
像 HotSpot VM 这样的实现,直到 Java 7,用于将方法区存储为堆的一部分。但是从Java8开始,它被移出堆,分配给堆的space没有被方法区消耗。

What happens to for example the constructor?

构造是具有特殊名称的方法,称为 <init>.1。它们的存储方式与其他方法相同。
作为旁注,有一个 class 初始化方法,称为 <clint>,它处理 class.2

中的静态块