static【静态】关键字
特点:
- 随着类的加载而加载
- 优先于对象存在
- 被类的所有对象共享
使用场景:
如果某个成员变量是被所有对象共享的,那么它就应该定义为静态的。
例如:饮水机用静态修饰;水杯不能用静态修饰。
存储:
成员变量在堆里,而静态属性不存储在堆里,它存储在方法区里。
静态属性正确的访问方式:类名.属性
例子:
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name ="Cynthia";
s1.say();
Student.classname="class 1";
s1.say();
Student s2 = new Student();
s2.name ="Cat";
s2.say();
Student.classname ="class 2";
s2.say();
s1.say();
}
}
class Student{
static String classname;
String name;
public void say(){
System.out.println("I am "+ this.name+", I come from "+this.classname);
}
}
以上代码运行结果:
I am Cynthia, I come from null
I am Cynthia, I come from class 1
I am Cat, I come from class 1
I am Cat, I come from class 2
I am Cynthia, I come from class 2
在静态方法中不能用this。
this是指向堆的一个对象,如果没有new 一个对象出来,怎么办?所以永远不要在静态方法中使用this。
静态方法只能访问静态成员变量和静态的成员方法。
静态成员变量只能访问静态成员方法。
网友评论