[英]what does static here refer to in java
很生锈,但我很确定我从未见过这样写的代码。 这是来自Java联考的一个模拟问题,有人可以告诉我第10行中的“静态”是否已连接到go()方法? 主要是为什么输出是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 ");
}
}
告诉我第10行中的“静态”是否已连接到go()方法?
它与go方法无关。 它称为静态初始化块。
为什么输出是xycg?
以下是Java中的执行顺序
static
块中有一个静态初始化块,将在加载类时运行。
http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
它是缩进的代码。 在以上课程中,您有
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 ");
}
}
静态块将在类加载时首先初始化。 那就是你得到o / p的原因
x as the first output
它是静态初始化块。 因此,当您创建该类的对象时,它甚至会在构造函数之前先运行静态初始化块。
static { System.out.print("x "); }
这是静态初始化程序块。 这将在类加载时调用。 因此,第一个电话。
{ System.out.print("y "); }
这是非静态初始化程序块。 创建对象后将被称为第一件事。
testclass() { System.out.print("c "); }
这是构造函数。 所有初始化程序块执行完后,将在对象创建过程中执行。
最后,
void go() { System.out.print("g "); }
普通方法调用。 最后要执行的事情。
有关更多详细信息,请参阅http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.