class Student {
String name;
int age;
private static Student stu = new Student();
private Student() {//构造方法私有化,外部类不能访问
}
public static Student getStudent() {
return stu;
}
public void showInfo(){
System.out.println(this);
}
}
public class ThisDemo{
public static void main(String[] args) {
Student stu1 = null;
stu1 = Student.getStudent();
stu1.showInfo();
Student stu2 = null;
stu2 = Student.getStudent();
stu2.showInfo();
}
主类每次所创建的对象都是stu,而其中main方法打印了stu1和stu2,这个实验估计想告诉你这两个东西的内存是一样的.
就是说main类创建了两个对象stu1,stu2,但其实两个都是用了方法中的stu,stu不会被清除.
你在stu1中调用了stu,stu留下来的东西会给到stu2.就是两个对象指着同一个地址.
输出结果:
