java中这个代码块背后的基本原理是什么?

发布于 2024-10-20 02:31:47 字数 217 浏览 1 评论 0原文

使此类代码在 java 中有效的原理是什么?它的存在是否出于某种特定原因,或者只是其他 Java 语言设计决策的副产品?直接使用构造函数就不能达到同样的效果吗?

class Student
{
    {
        System.out.println("Called when Student class is instantiated.");
    }
}

What is the rationale behind making this kind of code valid in java? Does it exist for some particular reason or is it just a byproduct of other Java language design decisions? Can't you just use the consructor to achieve the same effect?

class Student
{
    {
        System.out.println("Called when Student class is instantiated.");
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

墨小沫ゞ 2024-10-27 02:31:47

一点是,无论调用哪个构造函数,它都会执行。如果您有多个构造函数并且它们不会相互调用(无论出于何种原因,例如每个都想调用直接对应的超类构造函数),这是确保为所有构造函数执行相同代码的一种方法,而不会将其放入可以在其他地方调用的方法。

当您编写匿名类时,它也可能很有用 - 您无法编写构造函数,但您可以编写初始化程序块。例如,我见过它用于 JMock 测试。

One point is that it will execute whichever constructor is called. If you have several constructors and they don't call each other (for whatever reason, e.g. each wanting to call a directly-corresponding superclass constructor) this is one way of making sure the same code is executed for all constructors, without putting it in a method which could be called elsewhere.

It's also potentially useful when you're writing an anonymous class - you can't write a constructor, but you can write an initializer block. I've seen this used for JMock tests, for example.

生生不灭 2024-10-27 02:31:47

它称为初始化块

Java 编译器将初始化块复制到每个构造函数中。因此,这种方法可用于在多个构造函数之间共享代码块。

It's called an initializer block.

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

十雾 2024-10-27 02:31:47

它称为初始化块。在这样的块中,您可以执行与所有构造相同的逻辑,也可以分离相同字段的声明初始化

upd 当然还有双括号初始化,例如

List<Integer> answers = new ArrayList<Integer>(){{add(42);}}

It called init block. In such block you can perform logic that are same for all constructions also you can separate declaration and initialization of same fields.

upd and of course double brace initialization, like

List<Integer> answers = new ArrayList<Integer>(){{add(42);}}
江南烟雨〆相思醉 2024-10-27 02:31:47

这是一个初始化块。正如 Matt Ball 所提到的,它们被复制到每个构造函数中。

您可能有兴趣了解静态初始化块(也在 Matt 的 链接):

public class Foo {
    static {
        System.out.println("class Foo just got initialized!");
    }

    {
        System.out.println("an instance of Foo just got initialized!");
    }
}

This is an initialization block. As mentioned by Matt Ball, they are copied into each constructor.

You might be interested to know about static initialization blocks (also in Matt's link):

public class Foo {
    static {
        System.out.println("class Foo just got initialized!");
    }

    {
        System.out.println("an instance of Foo just got initialized!");
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文