一、static关键字
static是Java中的一个关键字,单词本身是静态的含义。一个类的成员包括变量、方法、构造方法、代码块和内部类,static可以修饰除了构造方法以外的所有成员。
使用static修饰的成员称为静态成员,是属于某个类的;而不使用static修饰的成员称为实例成员,是属于类的每个对象的。
1.1 static变量
在类中,用static声明的成员变量称为静态成员变量,也称为类变量。 类变量的生命周期和类相同,在整个应用程序执行期间都有效。它有如下特点:
- 为该类的公用变量,属于类,被该类的所有实例共享,在类被载入时被显式初始化。
- 对于该类的所有对象来说,static成员变量只有一份。被该类的所有对象共享!
- 一般用“类名.(点)类属性/方法”来调用。(也可以通过对象引用或类名(不需要实例化)访问静态成员。)
- 在static方法中不可直接访问非static的成员。
【示例1】static变量
public class Student {
//成员变量
private int sno;//学号
private String name;//姓名
private String sex;//性别
private double score;//分数
private String cup;//杯子
//private static String waterDispenser;//饮水机
private static String classRoom;//教室的编号
//private static String teachName;//讲师的名字//构造方法
public Student(){
}
public Student(int sno, String name, String sex ){
this.sno = sno;
this.name = name;
this.sex = sex;
}
public void show(){
System.out.println(sno +" "+this.name+" "+sex+" "+this.score+" "+classRoom);
}
public static void main(String[] args) {
System.out.println(Student.classRoom);
Student.classRoom = "503";
System.out.println(Student.classRoom);
Student stu = new Student(7,"田七","男",77);
stu.sno = 5;
//Student.sno = 6;
stu.classRoom = "507";
stu.show();
Student stu2 = new Student();
stu2.show();
}
}
内存分配图如下:
总结:
static变量和非static变量的区别:
static | 非static | |
---|---|---|
份数不同 | 1份 | 1个对象一份 |
存储位置不同 | 方法区中 | 堆中 |
内存分配空间的时间不同 | 第一次类被加载的时候 | 创建对象的时候 |
生命周期不同 | 和类的生命周期相同 | 和所属的对象生命周期相同 |
调用方式不同 | 1.通过类名调用 Student.classRoom 2. 通过对象名调用 stu1.classRoom=“301”(不推荐使用) | 通过对象名调用 stu1.name=“小张” |
1.2 static方法
- 作用:访问static变量和static方法
- 调用方式:
通过类名调用 Student.showClassRoom(); 推荐该方式
通过对象名访问 stu1.showClassRoom(); - 不可以访问的三种情况:
静态方法中不可以访问非静态变量
静态方法中不可以访问非静态方法
静态方法中不可以访问this
理解: 加载类的时候就加载静态变量和静态方法,此时可能还没有创建对象,所以非静态变量和非静态的方法还没有分配空间,因此无法访问。 - 两个可以:
非静态方法中可以访问静态变量
非静态方法中可以访问静态方法
理解: 加载类的时候就已经加载静态变量和静态方法,创建对象后,非静态变量和非静态的方法才分配空间,此时静态变量和静态方法已经存在,因此可以访问。
【示例2】static方法
public class Student {
//成员变量
String name;
int age;
String sex;
double score;
static String classRoom;//103 !!!
public static void showClassRoom(){
System.out.println(classRoom);
//System.out.println(name);//非静态变量
//shout();//非静态方法
//System.out.println(this); }
public static void setClassRoom(String classRoom){
Student.classRoom = classRoom;
}
//成员方法
public void introduce(){
System.out.println(this.name+" "+this.age+" "+sex+" "+score+" "+classRoom);
showClassRoom();
}
public static void main(String[] args) {
Student.showClassRoom();
Student.setClassRoom("r301");
Student.showClassRoom();
//Student stu1 = new Student("小王",20,"男",98);
Student stu1 = new Student("小王",20,"男");
stu1.name ="小张";
stu1.classRoom ="r301";
stu1.showClassRoom();
}
}