在Java中,代码块使用“{}”,一般分为四种:普通代码块、构造块、静态块、同步代码块。
4. 不使用main函数输出语句
1. 普通代码块,属于函数。 一般写在函数之中,随着函数的执行按照正常的流程执行
public
static
void main(){
{
int m = 100;
System.out.println( "静态代码块中的语句, x="+x);
}
int m =1;
System.out.println( "x="+x);
}
{
int m = 100;
System.out.println( "静态代码块中的语句, x="+x);
}
int m =1;
System.out.println( "x="+x);
}
2. 构造块, 属于类。构造块回报多次重复调用,且优先于构造方法执行。
class Example{
{
System.out.println( "----构造块---");
}
public Example(){
System.out.println( "----构造方法----");
}
}
{
System.out.println( "----构造块---");
}
public Example(){
System.out.println( "----构造方法----");
}
}
3. 静态块, 使用static关键字修饰的代码块成为静态块。主要目的用于静态属性的初始化。 静态块优先于主方法执行, 优先于构造块执行,且执行一次。
class Demo{
{ // 构造块
System.out.println( "*构造块 *") ;
}
static{
System.out.println( "** 类中的静态块 **") ;
}
public Demo(){ // 构造方法
System.out.println( "*** 构造方法 ***") ;
}
};
public class CodeDemo03{
static{
System.out.println( "**** 主类中的静态块 ****") ;
}
public static void main(String args[]){
new Demo() ;
new Demo() ;
new Demo() ;
}
};
{ // 构造块
System.out.println( "*构造块 *") ;
}
static{
System.out.println( "** 类中的静态块 **") ;
}
public Demo(){ // 构造方法
System.out.println( "*** 构造方法 ***") ;
}
};
public class CodeDemo03{
static{
System.out.println( "**** 主类中的静态块 ****") ;
}
public static void main(String args[]){
new Demo() ;
new Demo() ;
new Demo() ;
}
};
static{
System.out.println( "Hello World!!!") ;
System.exit(1) ;
}
System.out.println( "Hello World!!!") ;
System.exit(1) ;
}
本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/246165,如需转载请自行联系原作者