【问题标题】:StackOverFlow Error in Instantiating an Object实例化对象时的 StackOverFlow 错误
【发布时间】:2012-08-27 03:38:31
【问题描述】:

我正在复习认证考试,并尝试了以下代码:

class A {   
    B b = new B();
    static {
        System.out.println("A static.");
    }
    {
        System.out.println("A instance.");
    }
    A() {
        System.out.println("A constructor.");
    }
}
class B extends A {
    static {
        System.out.println("B static.");
    }
    {
        System.out.println("B instance.");
    }
    B() {
        System.out.println("B constructor.");
    }
}

public class Raaawrrr {
    public static void main(String args[]) {
        A a = new A();
    }
}

打印出来:

一个静态的。 B 静态的。

然后导致堆栈溢出。我很难理解为什么。你能帮帮我吗?

【问题讨论】:

  • 一个类不应继承自包含它的类。没有意义。
  • 绝对没有意义。但是很多认证问题也没有意义,我只是想在这里理解一些概念。

标签: java static constructor stack-overflow


【解决方案1】:

A 实例化 B。B 恰好也是 A 类型,因此再次实例化。哪个实例化 B... 等等。

【讨论】:

    【解决方案2】:

    您正在创建一个类 B 的对象,它是类 AA 的子类。请注意,超类的构造函数必须在子类构造函数执行之前执行。

    【讨论】:

      猜你喜欢
      • 2019-11-01
      • 1970-01-01
      • 2011-03-21
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多