没办法调用任何构造函数?
问题说明
public class Test {
public static void main(String args[]){
System.out.println("Main");
Test2 test2 = new Test2();
}
}
class Test2 {
Test2() {
System.out.println("Inside Test2");
//do something
}
Test3 test = new Test3();
}
class Test3 {
Test3() {
System.out.println("Inside Test3");
//do something
}
Test2 test2 = new Test2();
}
在这里我想了解为什么为什么 Test
类的主要方法中的 Test2 test2 = new Test2();
语句不能调用类的构造函数> Test2
和类似地 Test2
中的 Test3 test = new Test3();
无法调用类 Test3
的构造函数.
Here I wanted to understand why this statement Test2 test2 = new Test2();
in main method of class Test
is not able to invoke the constructor of class Test2
and similarly Test3 test = new Test3();
in Test2
is not able to invoke the constructor of class Test3
.
我想了解这种行为的原因吗?
Here I wanted to understand the reason for this behavior?
预期输出: Test2里面的主要内容
当前输出: Main
并显示错误
Expected Output : Main Inside Test2 Inside Test3
Current Output: Main
with this error
Exception in thread "main" java.lang.StackOverflowError
at com.practice.stackoverflow.Test3.<init>(Test.java:26)
at com.practice.stackoverflow.Test2.<init>(Test.java:17)
at com.practice.stackoverflow.Test3.<init>(Test.java:26)
正确答案
Test2
创建一个新的 Test3
对象...从而创建一个新的 Test2
对象...等等.
Test2
makes a new Test3
object... which makes a new Test2
object... so on.
您尝试创建无限数量的对象,因此自然会收到StackOverflowError.
You are attempting to create an infinite amount of objects, so naturally you will get a StackOverflowError.
以下方法将起作用:
public class Test {
public static void main(String args[]){
System.out.println("Main");
Test2 test2 = new Test2();
}
}
class Test2 {
Test2() {
System.out.println("Inside Test2");
//do something
}
Test3 test = new Test3();
}
class Test3 {
Test3() {
System.out.println("Inside Test3");
//do something
}
Test4 test4 = new Test4();
}
class Test4 {
Test4() {
System.out.println("Inside Test4");
}
}
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcakkff
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20