您的位置:首页 > 编程语言 > Java开发

java之静态代码块、构造块、构造方法的简单例子

2015-06-09 21:44 477 查看
啥也不说直接贴代码!

public class Person {

private String name;

private int age;

public Person() {
System.out.println("this is a person");
}

{
System.out.println("this is a constructor block");
}

static {
System.out.println("this is a staitc block");
}

public Person(String name, int age) {
this();
this.name = name;
this.age = age;
System.out.println("his name is " + this.name + "his age is"
+ this.age);
}

public static void main(String args[]) {
Person a = new Person();
Person b = new Person("haha", 18);
}


}

运行结果如下:

this is a staitc block
this is a constructor block
this is a person
this is a constructor block
this is a person
his name is haha  his age is 18


可以发现静态代码块是最先执行的,而且仅仅执行一次,在伪编译生成.class文件的时间就运行。

接下来是构造块的执行,最然后是构造方法的执行,随着生成新的实例,构造块每次都会执行一次。

public class Test {
static {
System.out.println("hello world");
System.exit(1);
}
}


类似于这段代码,但是在java8中已经不能运行了。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  构造方法 代码 java