• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

没办法调用任何构造函数?

用户头像
it1352
帮助5

问题说明

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)

正确答案

#1

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
系列文章
更多 icon
同类精品
更多 icon
继续加载