static关键字的使用
概述
- static表示“静态”的意思,可以用来修饰成员变量和成员方法。
- static的主要作用在于创建独立于具体对象的域变量或者方法。
- 简单理解:
被static关键字修饰的方法或者变量不需要依赖于对象来进行访问,只要类被加载了,就可以通过类名去进行访问。
并且不会因为对象的多次创建而在内存中建立多份数据。
特点
- 静态成员在类加载时加载并初始化。
- 优先于对象而存在
- 无论一个类存在多少个对象 , 静态的属性, 永远在内存中只有一份( 可以理解为所有对象公用 )。
- 可以使用类名直接调用,静态方法可以使用类名直接调用,静态变量可以使用类名进行修改,也可以使用对象引用进行修改,方法区中存储的永远只有最后一次修改的结果,中间修改的结果不会被存储!
- 在访问时:静态不能访问非静态 , 非静态可以访问静态!因为静态比非静态加载得早,非静态需要等到对象创建时,才被初始化
举个栗子

static关键字修饰成员变量
- 如果一个成员变量使用了static关键字,那么这个变量不再属于对象自己,而是属于所在的类。多个对象共享同一份数据。
public class Student {
private int age;
private String name;
satitc String room = "101教室";
...
}
public class StudentTest {
public static void main(String[] args) {
Student one = new Student();
Student two = new Student();
Student three = new Student();
System.out.println(one.room);
System.out.println(two.room);
System.out.println(three.room);
/这里的学生对象one,two,three,共享的是同一份Student类里面的room数据
}
}
注意
- 静态成员变量可以被修改,结果为最后一次修改的结果!不会因为对象的不同而同时存在多份!
...
Student one = new Student();
Student two = new Student();
Student three = new Student();
one.room = "102教室";
two.room = "103教室";
three.room = "104教室";
System.out.println(one.room);
System.out.println(two.room);
System.out.println(three.room);
...
static关键字修饰成员方法
- 静态方法里面可以访问静态变量,但是不可以直接访问非静态变量。
- 静态方法里面不可以有this关键字!this关键字有表示对象的作用,由于静态方法是优先于对象存在的,所以会出现逻辑错误!
public class Myclass {
int num;
static int numStatic;
public static void methodStatic(){
System.out.println(numStatic);
System.out.println(num);
System.out,println(this);
}
public void method(){
System.out.println(num);
System.out.println(numStatic);
}
}