static案例代码:
代码:
public class Student {private String gender;private String name;private int age;public static String teacherName ;public Student() {}public Student(String gender, String name, int age) {this.gender = gender;this.name = name;this.age = age;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public void study(){System.out.println(name + "正在学习");}public void show(){System.out.println(name + "," + age +","+ gender + ","+ teacherName);}
}
public class test{public static void main(String[] args) {Student.teacherName = "阿伟老师";//类名调用Student s1 = new Student();s1.setName("张三");s1.setAge(23);s1.setGender("男");//s1.teacherName="阿伟老师";对象名调用s1.study();s1.show();Student s2 = new Student();s2.setName("李四");s2.setAge(24);s2.setGender("男");s2.study();s2.show();}
}
运行结果:
static内存图:
在执行main方法的第一个语句时,是用类名调用了Student方法中的静态变量teacherNmae并赋值为阿伟老师,用到了Student这个类,所以就会把Student类的字节码文件加载到方法区,并在内存中创建了一个单独存放静态变量的空间,即为静态区。
在jdk8之前,静态区在方法区里面,在jdk8以后就存存放在了堆里面。
静态区随着类的加载而加载,只有new关键字执行了才有对象,所以静态变量优先于对象而存在的。
在堆中创建的空间,存储的是所有的非静态成员变量;
方法发执行完毕,出栈
静态:共享
在不同的场景下,思考是否可以共享;