调用没有名称的Java方法 [英] Calling a Java method with no name

查看:130
本文介绍了调用没有名称的Java方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看下面的代码并发现有点奇怪的事情:

I'm looking at the code below and found something a bit strange:

public class Sequence {
    Sequence() {
        System.out.print("c ");
    }

    {
        System.out.print("y ");
    }

    public static void main(String[] args) {
        new Sequence().go();
    }

    void go() {
        System.out.print("g ");
    }

    static {
        System.out.print("x ");
    }
}

我希望这会给出编译错误因为带有y的 System.out 不属于方法声明只是 {} 。为什么这个有效?我看不出这个代码是如何被调用的。

I would've expected this to give a compilation error as the System.out with "y " doesn't belong to a method declaration just a { }. Why is this valid? I don't see how this code would or should be called.

当运行它时,它也产生 xycg ,为什么在序列构造函数之前调用 static {}

When running this it produces x y c g also, why does the static { } get called before the sequence constructor?

推荐答案

这个:

static {
        System.out.print("x ");
    }

是一个静态初始化块,并被调用当类加载时。你可以在你的课堂上拥有它们中的任意一个,并且它们将按照它们的外观顺序执行(从上到下)。

is a static initialization block, and is called when the class is loaded. You can have as many of them in your class as you want, and they will be executed in order of their appearance (from top to bottom).

这个:

    {
        System.out.print("y ");
    }

初始化块,代码是复制到类的每个构造函数的开头。因此,如果您的类中有许多构造函数,并且它们都需要在开头时执行一些常见操作,则只需编写一次代码并将其放在初始化块中。

is an initialization block, and the code is copied into the beginning of each constructor of the class. So if you have many constructors of your class, and they all need to do something common at their beginning, you only need to write the code once and put it in an initialization block like this.

因此您的输出非常有意义。

Hence your output makes perfect sense.

As Stanley 在下面评论,请参阅该部分在Oracle教程中描述初始化块以获取更多信息。

As Stanley commented below, see the section in the Oracle tutorial describing initializaiton blocks for more information.

这篇关于调用没有名称的Java方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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