- public class Test5 {
- private static int a;
- private int b;
- static{
- Test5.a=3;
- System.out.println(a);
- Test5 t=new Test5();
- t.f();
- t.b=1000;
- System.out.println(t.b);
- }
- static{
- Test5.a=4;
- System.out.println(a);
- }
- public static void main(String[] args) {
- }
- static{
- Test5.a=5;
- System.out.println(a);
- }
- public void f(){
- System.out.println(“hhahhahah”);
- }
- }
- public class Test5 {
- private static int a;
- private int b;
- static{
- Test5.a=3;
- System.out.println(a);
- Test5 t=new Test5();
- t.f();
- t.b=1000;
- System.out.println(t.b);
- }
- static{
- Test5.a=4;
- System.out.println(a);
- }
- public static void main(String[] args) {
- }
- static{
- Test5.a=5;
- System.out.println(a);
- }
- public void f(){
- System.out.println(“hhahhahah”);
- }
- }
运行结果:
3
hhahhahah
1000
4
5
分析:
static 代码块也叫静态代码块,是在类中独立于类成员的static语句块,可以有多个,位置可以随便放,它不在任何的方法体内,JVM加载类时会执行这些静态的 代码块,如果static代码块有多个,JVM将按照它们在类中出现的先后顺序依次执行它们,每个代码块只会被执行一次 ( 我记得蓝色之路里就有这么一道类似的变态题目)
————————————————————-
http://yahaitt.iteye.com/blog/143457
静态代码块的执行顺序
补充:
在有类内非静态代码块的情况下,执行顺序应该如下:
静态代码块的执行顺序:
1.父类的静态代码块
2.子类的静态代码块
3.父类的非静态代码块
4.父类的构造函数
5.子类的非静态代码块
6.子类的构造函数
================================================
- //静态代码块的执行顺序
- import static java.lang.System.out;
- class Bird
- {
- public Bird()
- {
- out.print(“b2 “);
- }
- {out.print(“b1 “);}
- static
- {
- out.print(“bs0 “);
- }
- }
- class Raptor extends Bird
- {
- static
- {
- out.print(“rs1 “);
- }
- public Raptor()
- {
- out.print(“r2 “);
- }
- {
- out.print(“r3 “);
- }
- static
- {
- out.print(“rs4 “);
- }
- }
- public class G015 extends Raptor{
- public static void main(String[] args) {
- out.print(“pre “);
- new G015();
- out.println(“G015 “);
- }
- }
- //静态代码块的执行顺序
- import static java.lang.System.out;
- class Bird
- {
- public Bird()
- {
- out.print(“b2 “);
- }
- {out.print(“b1 “);}
- static
- {
- out.print(“bs0 “);
- }
- }
- class Raptor extends Bird
- {
- static
- {
- out.print(“rs1 “);
- }
- public Raptor()
- {
- out.print(“r2 “);
- }
- {
- out.print(“r3 “);
- }
- static
- {
- out.print(“rs4 “);
- }
- }
- public class G015 extends Raptor{
- public static void main(String[] args) {
- out.print(“pre “);
- new G015();
- out.println(“G015 “);
- }
- }
输出结果应为:
bs0 rs1 rs4 pre b1 b2 r3 r2 G015
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/13806.html