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

Java的static关键字

2015-02-06 20:33 204 查看

1.可以修饰的对象有:变量,方法,代码块,(引入包名)

对应的就是:静态变量/类变量;静态方法;静态代码

eg: public class Student{

public static int a = 0;

public static int getValue(){

return a;

}

}

静态引入包名:

public class User {
private static int userNumber  = 0 ;

public User(){
userNumber ++;//每创建一个对象就加1
}

public static void main(String[] args) {
User user1 = new User();//此时 userNumber为1
User user2 = new User();//此时 userNumber为2

System.out.println("user1 userNumber:" + User.userNumber);
System.out.println("user2 userNumber:" + User.userNumber);
}
}
------------
Output:
user1 userNumber:2
user2 userNumber:2


View Code

3.可以直接用类名来访问,而不必实例一个对象才能使用。

eg: Student.getValue();//直接类名调用

或者 Student s = new Student();

s.getValue();//也可以通过先生成实例再调用,但推荐第一种

4. 使用static要注意的

4.1. static变量在定义时必须要进行初始化,且初始化时间要早于非静态变量。

4.2. static修饰的方法,只能调用static变量或方法,而不能调用非static的变量或方法。

4.3.不能以任何形式引用this、super。(因为它们也不是static的)

总结:无论是变量,方法,还是代码块,只要用static修饰,就是在类被加载时就已经"准备好了",也就是可以被使用或者已经被执行,都可以脱离对象而执行。

反之,如果没有static,则必须要依赖于对象实例,记住两点,凡是static只有两层含义,静态/共享

参考这里非常详细
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: