在java中使用非静态块有什么用? [英] What is the use of non-static block in java?

查看:116
本文介绍了在java中使用非静态块有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

实例初始值设定项与构造函数有何不同?

当所有必需的工作都可以在构造函数内完成时,为什么我们仍然需要Java中的非静态块?

When all the required work can be done inside the constructor, then why do we still need non-static block in Java?

编辑:在构造函数之前每次运行非静态块的普通类怎么办?

What about normal classes for which non-static blocks run everytime before the constructor?

推荐答案

除了@ Bohemian的答案之外。

In additional to @Bohemian's answer.

如果您有多个构造函数,则一个intialiser块可以避免重复。

If you have multiple constructors an intialiser block avoid duplication.

public class A {
     final Map<String, String> map = new HashMap<String, String>(); {
        // put things in map.
     }
     final int number; {
        int number;
        try {
            number = throwsAnException();
        } catch (Exception e) {
            number = 5;
        }
        this.number = number;
     }

     public A() { /* constructor 1 */ }
     public A(int i) { /* constructor 2 */ }
}




在构造函数之前每次运行非静态块的普通类怎么样?

What about normal classes for which non-static blocks run everytime before the constructor?

从技术上讲,订单是


  • 总是先调用超级构造函数

  • 所有初始化程序块。

  • 构造函数代码

实际上所有这些代码都在每个构造函数的字节代码中,因此在运行时构造函数之前或之后都没有。

In reality all this code is in the byte code for each constructor so there is nothing before or after the constructor at runtime.

在对初始化顺序有任何疑惑之前

Before there is any more confusion as to the order of initialization

public class Main extends SuperClass {
    {
        System.out.println("Initialiser block before constructor");
    }

    Main() {
        System.out.println("Main constructor");
    }

    {
        System.out.println("Initialiser block after constructor");

    }

    public static void main(String... args) {
        new Main() {{
            System.out.println("Anonymous initalizer block");
        }};
    }
}

class SuperClass {
    SuperClass() {
        System.out.println("SuperClass constructor");
    }
}

打印

SuperClass constructor
Initialiser block before constructor
Initialiser block after constructor
Main constructor
Anonymous initalizer block

这篇关于在java中使用非静态块有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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