<<java编程思想>>:
1、static方法就是没有this的方法。
2、在static方法内部非静态方法。
3、在没有创建对象的前提下,可以通过类本身来调用static修饰的方法。
a.static它的特性:只会在类加载的时候执行一次。static成员变量的初始化顺序按照定义的顺序进行初始化
b.static 代码块可以优化程序性能,它的特性:只会在类加载的时候执行一次。很多时候,初始化操作我们都放在静态块中。
练习:
1.this代表的是当前对象,static修饰的变量是被对象享有的。而方法里面的变量是局部变量,不能申明为static.
public class Test1 { static int value = 88; public static void main(String[] args) throws Exception{ new Test1().printValue(); } private void printValue(){ int value = 99; System.out.println(this.value); } }
执行结果为 88.
2.静态方法中不能访问非静态成员方法和非静态成员变量
private static int a=1; private int b=1; public static void test1(){ System.out.println(a); System.out.println(b); //1错误 test2();//2错误 } public void test2(){ System.out.println(a); System.out.println(b); test1(); }
3.子类,父类静态代码块,构造方法执行顺序。
/** * @author tangquanbin */ public class Dad { static { System.out.println("dad static"); } public Dad() { System.out.println("dad constructor"); } }
/** * @author tangquanbin */ public class Son extends Dad { static { System.out.println("son static"); } public Son() { System.out.println("son constructor"); } }
/** * @author tangquanbin */ public class Test { public static void main(String[] args) { Son son = new Son(); } }
输出结果:
dad static
son static
dad constructor
son constructor