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

java中static学习总结

2015-10-22 11:40 387 查看
<<java编程思想>>。

static作用:

1.在没有创建对象时,调用staitic修饰的方法或变量(B包中类有static方法或static变量,可以在A包中的类里通过类名调用这些方法或变量,它的实质就是,static它的特性:只会在类加载的时候执行一次。)

2.static 代码块可以优化程序性能,它的特性:只会在类加载的时候执行一次。很多时候,初始化操作我们都放在静态块中。

3.类的构造器实际上也是静态方法。

练习:

1.

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. this代表的是当前对象,static修饰的变量是被对象享有的。而方法里面的变量是局部变量,不能申明为static.

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();
}


静态方法中不能访问非静态成员方法和非静态成员变量
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: