在Java中使用static关键字创建对象 [英] Creating object using static keyword in Java

查看:346
本文介绍了在Java中使用static关键字创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class abc {
    int a = 0;
    static int b;
    static abc h = new abc(); //line 4

    public abc() {
        System.out.println("cons");
    }

    {
        System.out.println("ini");
    }

    static {
        System.out.println("stat");
    }
}

public class ques {
    public static void main(String[] args) {
        System.out.println(new abc().a);
    }
}

当我写这段代码时,我按顺序输出像这样:

When i wrote this code I am getting output in order like this:

ini
cons
stat
ini
cons
0

这时我在 main()中创建了一个新对象, class abc 已加载, static 变量和块按写入顺序执行。当控制进入第4行 static abc h = new abc(); 调用实例初始化块。为什么?为什么在第4行创建一个新对象时没有调用静态块,直到那时静态块也没有被调用一次,所以根据惯例静态块应该被调用。为什么会出现意外输出?

Here when I created a new object in main(), class abc got loaded and static variables and blocks are executed in order they are written. When control came to line 4 static abc h = new abc(); Instance Initialization block is called. Why? why is static block not called when a new object is created at line 4 and till that time static block was also not called even once, so according to convention static block should have been called. Why is this unexpected output coming?

推荐答案

静态字段初始化和静态块按声明的顺序执行。在您的情况下,代码在分离声明和初始化后等效于此:

Static fields initialization and static blocks are executed in the order they are declared. In your case, the code is equivalent to this after separating declaration and initialization:

class abc{
    int a;
    static int b;
    static abc h;//line 4

    static {
        h = new abc();//line 4 (split)
        System.out.println("stat");
    }

    public abc() {
        a = 0;
        System.out.println("ini");
        System.out.println("cons");
    }
}

public class ques{
    public static void main(String[] args) {
        System.out.println(new abc().a);
    }
}

所以当你从你的代码到达第4行时,静态初始化实际上正在执行但尚未完成。因此,在 stat 可以打印之前调用构造函数。

So when you reach line 4 from your code, the static initialization is actually being executed and not finished yet. Hence your constructor is called before stat can be printed.

这篇关于在Java中使用static关键字创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆