我知道在 Java 中所有的方法调用都在栈上。以下面的类为例:
Class Demo
{
// Some instance variables
public Demo()
{
initialize();
}
public void initialize()
{
// Start initialization
....
// Call another method to perform some complex calculation
int resultVal = helperMethod();
// Perform the remaining initialization work
}
public int helperMethod()
{
// Perform some complex calculation
....
return result;
}
}
第一个initialize()
(及其状态)被压入堆栈,然后当它调用 helperMethod()
时,状态helperMethod()
也被压入堆栈。
但我想了解的是 Demo()
的状态首先 被压入堆栈(甚至在 initialize()
被压入之前),尽管它是构造函数而不是方法?
保存构造函数状态和方法状态之间有显着差异吗?
最佳答案
归根结底,构造函数就像任何其他方法一样。它接受任何类型的参数并返回它自己类型的对象。它像其他任何东西一样放在调用堆栈上,并显示为 Demo.<init>()
您的示例调用堆栈跟踪中的异常看起来像
Exception in thread "main" java.lang.NullPointerException
at Demo.helperMethod(Demo.java:30)
at Demo.initialize(Demo.java:16)
at Demo.<init>(Demo.java:7) <---------
at Demo.main(Demo.java:36)
关于java - 构造函数调用是否也进入堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31619846/