java自己创建类,java – 在自己的静态初始化程序中创建类的对象

根据

JLS:

A class or interface type T will be initialized immediately before the

first occurrence of any one of the following:

T is a class and an instance of T is created.

也说,

Initialization of a class consists of executing its static

initializers and the initializers for static fields (class variables)

declared in the class

我从中推断出两点

>类初始化包括执行其静态初始化器

>如果类实例化,则会发生类初始化。

现在,

我假设当我自己创建一个Test(测试自己的)静态初始化器的对象时,它应该给我一个堆栈溢出,因为它应该重复调用自己,因为根据上述两点,类的实例化应该初始化类,初始化块具有类的实例化。当我在自己的构造函数或其自己的实例初始化器中实例化类时,会发生堆栈溢出。

例如,

public class Test {

static{

System.out.println("static test");

new Test();

}

{

//new Test(); // This will give a stack overflow

System.out.println("intializer");

}

public Test(){

//new Test(); // This will give a stack overflow

System.out.println("constructor");

}

public static void main(String[] args) {

}

}

然而结果却有所不同。

结果:

static test

intializer

constructor

要么我对这个课程的初始化感到太困惑,要是我在这里遗漏了一些非常明显的东西,并且感谢您的帮助,我们深表歉意。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值