java – Instance Initialiser中的StackOverflowError
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – Instance Initialiser中的StackOverflowError,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2274字,纯文字阅读大概需要4分钟。
内容图文
![java – Instance Initialiser中的StackOverflowError](/upload/InfoBanner/zyjiaocheng/806/dd5026558d674fe4b6e5dc68a3ae6893.jpg)
这个问题更具理论性.所以我有以下一组代码:
public class Test {
public static void main(String[] args) {
Test test = new Test();
}
{
System.out.println("Instance execution");
}
}
它编译并打印“实例执行”.
但是当我尝试以这种方式执行其他方法时:
public class Test {
public static void main(String[] args) {
Test test = new Test();
}
{
System.out.println("Instance execution");
}
private void anotherMethod() {
System.out.println("Method execution");
}
{
Test test = new Test();
test.anotherMethod();
}
}
它给了我这个错误:
Exception in thread "main" java.lang.StackOverflowError
at Test.<init>(Test.java:15)
我完全相信这个错误有最简单的解释,但我的问题是,构造函数是否抛出这个错误?或者只有系统方法可以这样执行?可执行Instance Initialiser的整个方法对我来说都是新的,所以任何帮助都会非常感激.谢谢.
解决方法:
这个:
{
Test test = new Test();
test.anotherMethod();
}
是一个实例初始化程序块.它在每次创建Test实例时运行.在其中,你是……创建一个新的Test实例,它自然地触发了块,然后创建一个新的Test实例,触发块…你明白了.
is it the constructor that’s throwing this error?
这是实例初始化,是的.事实上,在封面下,编译器处理实例初始化程序块的方式是将该代码逐字地复制到类中每个构造函数的开头(包括默认代码,如果你不提供默认代码),在调用super之后(如果没有明确的调用,则为默认调用).所以你可以说它是抛出错误的构造函数,即使在概念上,它的实例初始化与构造函数本身是不同的.
Or only System methods can be executed this way?
不确定“系统方法”是什么意思,但问题是初始化程序块是按实例运行的.如果您希望它只运行一次,在类初始化时,您可以使用静态初始化程序块:
public class Test {
public static void main(String[] args) {
Test test = new Test();
}
{
System.out.println("Instance execution");
}
private void anotherMethod() {
System.out.println("Method execution");
}
static // <==================
{
System.out.println("Class initialization"); // ***
Test test = new Test();
test.anotherMethod();
}
}
那输出:
Class initialization Instance execution Method execution Instance execution
(我们看到“实例执行”两次,因为main中有一个新的Test,静态初始化块中有另一个.)
但实际上,最简单的方法是将调用另一个方法放在main中:
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.anotherMethod();
}
{
System.out.println("Instance execution");
}
private void anotherMethod() {
System.out.println("Method execution");
}
}
哪个输出
Instance execution Method execution
内容总结
以上是互联网集市为您收集整理的java – Instance Initialiser中的StackOverflowError全部内容,希望文章能够帮你解决java – Instance Initialiser中的StackOverflowError所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。