静态函数与静态变量无需生成对象
静态函数只能调用静态变量
装载类的时候执行静态代码块
静态函数中不能使用this
/* * For test static * 2014-10-26 */ public class JavaTest { public static void main(String args[]){ TestStatic.i = 10; //第一次赋值,未创建对象 TestStatic T1 = new TestStatic(); TestStatic T2 = new TestStatic(); //创建两个对象 System.out.println("The T1.i = " + T1.i); System.out.println("The T2.i = " + T2.i); T1.i = 20; //给其中一个对象的i赋值 System.out.println("Change the value of T1.i"); System.out.println("The T1.i = " + T1.i); System.out.println("The T2.i = " + T2.i); TestStatic.method1(); //查看目前的i值 } } class TestStatic{ static int i; static String arg1; static{ System.out.println("Now loading the 'TestStatic' class"); } static void method1(){ System.out.println("The current i is " + i); } }
输出结果:
Now loading the 'TestStatic' class
The T1.i = 10
The T2.i = 10
Change the value of T1.i
The T1.i = 20
The T2.i = 20
The current i is 20
----------------------------------------------------------------------------------------------------------------------
装载TestStatic类时,打印出了Now loading the 'TestStatic' class。对static int i赋值10,对象i的值都是10。
改变i的值,TestStatic对象的i值都会变。