静态static的内存图、静态代码块
静态static的内存图
我们来看一下static 的内存图,我们先来写一个示例
private String name;
private int age;
private String classroom;
public Student(String name, int age, String classroom) {
this.name = name;
this.age = age;
this.classroom = classroom;
}
public Student() {
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", classroom='" + classroom + '\'' +
'}';
}
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 String getClassroom() {
return classroom;
}
public void setClassroom(String classroom) {
this.classroom = classroom;
}
}
首先我们先创建一个学生类 ,写上有参 无参 和get set toString
然后我们在写一个测试类,在类中赋值
public static void main(String[] args) {
Student student = new Student("郭晓余", 1, "1" );
Student student1 = new Student("张小钱", 1, "1" );
System.out.println("班级:"+student.getAge());
System.out.println("学生名字:"+student.getName());
System.out.println("学生教室"+student.getClassroom());
System.out.println();
System.out.println("班级:"+student1.getAge());
System.out.println("学生名字:"+student1.getName());
System.out.println("学生教室"+student1.getClassroom());
}
}
我们来看一下运行结果
静态代码块
首先我们先来看什么是静态代码块
静态都知道了 可以被调用 那么代码块就是 在一个方法体中
来一下:
public class Student {
static {
System.out.println("你好世界");
}
}
用static修饰了的 方法体就是静态代码块
静态内容比构造方法先执行