2014-04-29 80 views
2

很生锈,但我很确定我从来没有见过这样写的代码。这是一个模拟问题从Java伙伴考试可能有人告诉我是否'静态'在第10行连接到go()方法?主要是为什么输出是x y c g ???静态在这里指的是什么

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 "); 
    } 

} 
+1

可能重复:http://stackoverflow.com/questions/2943556/static-block-in-java – user432

+0

'静态{}'被添加到的静态初始化类。当这个类被初始化时,它从上到下执行。 –

+0

ahh ..这就解释了为什么要首先打印x.谢谢ya'll – Leonne

回答

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

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 "); 
} 

} 
3

告诉我是否l中的'静态' ine 10连接到go() 方法??

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

为什么输出是x y c g ???

以下是执行在Java

  1. 在类加载时间的顺序,静态字段/初始化块将被执行。
  2. 在创建对象的时候,JVM领域设置为默认初始值(0,假,空)
  3. 调用构造函数对象(但不执行的身体构造的又)
  4. 调用使用初始值设定和初始化块超
  5. 初始化字段的构造
  6. 执行构造的主体
+0

这个问题的绝对副本(http ://stackoverflow.com/questions/13699075/calling-a-java-method-with-no-name),并应标记为重复 –

0

静态块将首先intialised作为类负载。多数民众赞成你得到O/P的原因

x as the first output 
0

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