2

相当生疏,但我很确定我从未见过这样写的代码。这是一个来自 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 ");
    }

} 
4

6 回答 6

3

告诉我第 10 行中的“静态”是否连接到 go() 方法?

它与 go 方法无关。它被称为静态初始化块。

为什么输出是 xycg ???

以下是java中的执行顺序

  1. 在类加载时,将执行静态字段/初始化块。
  2. 在对象创建时,JVM 将字段设置为默认初始值(0、false、null)
  3. 调用对象的构造函数(但不要执行构造函数的主体)
  4. 调用超类的构造函数
  5. 使用初始化器和初始化块初始化字段
  6. 执行构造函数的主体
于 2014-04-29T08:47:54.903 回答
2

static块有一个静态初始化块,将在加载类时运行。

http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

于 2014-04-29T08:48:36.707 回答
1

这是缩进很差的代码。在上面的课程中,您有

  1. 构造函数
  2. 一个类块
  3. 静态块
  4. 还有一个方法叫做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 "); 
} 

} 
于 2014-04-29T08:47:33.747 回答
0

静态块将在类加载时首先被初始化。这就是你得到 o/p 的原因

x as the first output
于 2014-04-29T08:48:52.067 回答
0

它是静态初始化块。因此,当您创建该类的对象时,它甚至在构造函数之前首先运行静态初始化块。

于 2014-04-29T08:49:02.893 回答
0
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

于 2014-04-29T08:53:02.883 回答