标签:pac sys 父类静态 静态代码块 静态 表示 子类 结果 ring
静态变量和静态方法
静态方法和静态变量都是类的静态资源,是类实例之间共享的。静态资源是类初始化的时候加载的,而非静态资源是实例初始化也就是new一个对象的时候加载的。所以:
静态块
静态块和静态变量/静态方法一样,也是在类初始化的时候执行,且只执行一次。静态块有三个需要注意的地方:
示例1:
package com.basic; public class StaticBlockTest { public static int a = test(); static { System.out.println("second"); } static { System.out.println("first"); } static int test() { System.out.println("third"); return 1; } public static void main(String[] args) { StaticBlockTest test = new StaticBlockTest(); } }
结果:
third
second
first
示例2:
package com.basic; public class StaticBlockTest { static int a = test(); static { System.out.println("second"); } static { System.out.println(b); } static int test() { System.out.println("third"); return 1; } static int b = 4; public static void main(String[] args) { StaticBlockTest test = new StaticBlockTest(); } }
编译器报错:“Cannot reference a field before it is defined“
示例3:
package com.basic; public class StaticBlockTest extends Father{ static int a = test(); static { System.out.println("second"); } static { // System.out.println(b); System.out.println("first"); } static int test() { System.out.println("third"); return 1; } static int b = 4; public void print() { System.out.println("Child"); } public static void main(String[] args) { StaticBlockTest test = new StaticBlockTest(); test.print(); } } class Father { static { System.out.println("Father"); } public void print() { System.out.println("Father"); } }
结果:
Father
third
second
first
Child
static修饰类
标签:pac sys 父类静态 静态代码块 静态 表示 子类 结果 ring
原文地址:http://www.cnblogs.com/IvySue/p/7488038.html