[英]what does static here refer to in java
pretty rusty but im pretty sure i've never seen a code written like this. 很生锈,但我很确定我从未见过这样写的代码。 it is a mock question from java associate exam could someone tell me whether the 'static' in line 10 is connected to the go() method??
这是来自Java联考的一个模拟问题,有人可以告诉我第10行中的“静态”是否已连接到go()方法? and mainly why is the output is xycg ???
主要是为什么输出是xycg ???
public class testclass {
testclass() {
System.out.print("c ");
}
{
System.out.print("y ");
}
public static void main(String[] args) {
new testclass().go();
}
void go() {
System.out.print("g ");
}
static {
System.out.print("x ");
}
}
tell me whether the 'static' in line 10 is connected to the go() method??
告诉我第10行中的“静态”是否已连接到go()方法?
It's not relevant to that go method. 它与go方法无关。 It's called as static initialization block.
它称为静态初始化块。
why is the output is xycg ???
为什么输出是xycg?
Following is the order of execution in java 以下是Java中的执行顺序
The static
block there is a static initialization block that will be run when the class is loaded. static
块中有一个静态初始化块,将在加载类时运行。
http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
It is poorly indented code. 它是缩进的代码。 In the above class you have
在以上课程中,您有
go()
go()
的方法 class testclass {
/**
* Constructor, which gets called for every new instance, after instance block
*/
testclass() {
System.out.print("c ");
}
/**
* This is instance block which gets called for every new instance of the class
*
*/
{
System.out.print("y ");
}
public static void main(String[] args) {
new testclass().go();
}
/**
* any method
*/
void go() {
System.out.print("g ");
}
/**
* This is static block which is executed when the class gets loaded
* for the first time
*/
static {
System.out.print("x ");
}
}
static blocks will be intialised first as the class loads. 静态块将在类加载时首先初始化。 thats the reason you get the o/p as
那就是你得到o / p的原因
x as the first output
It is static initialization block. 它是静态初始化块。 So when you create an object of that class it runs first the static initialization block even before the constructor.
因此,当您创建该类的对象时,它甚至会在构造函数之前先运行静态初始化块。
static { System.out.print("x "); }
This is the static initializer block. 这是静态初始化程序块。 This will be called at the time of class loading.
这将在类加载时调用。 Thus first call.
因此,第一个电话。
{ System.out.print("y "); }
This is non static initializer block. 这是非静态初始化程序块。 Will be called the first thing once a object is created.
创建对象后将被称为第一件事。
testclass() { System.out.print("c "); }
This is constructor. 这是构造函数。 Will be executed in the process of object creation, after all initializer blocks are executed.
所有初始化程序块执行完后,将在对象创建过程中执行。
Lastly, 最后,
void go() { System.out.print("g "); }
Normal method call. 普通方法调用。 Last thing to be executed.
最后要执行的事情。
For more details, please refer http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html 有关更多详细信息,请参阅http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.