目录
学生类
单个对象内存图
多个对象指向同一个内存地址
学生类
Student.java如下:
package com.面向对象;
public class Student {
String name;
int age;
public void work() {
System.out.println("开始敲代码...");
}
}
StudentDemo.java如下:
package com.面向对象;
public class StudentDemo {
public static void main(String[] args) {
Student mayiktStudent = new Student(); // new Student()存放堆内存,mayiktStudent存放在栈内存,直接引用到堆内存地址
System.out.println(mayiktStudent);
mayiktStudent.name = "mayikt";
mayiktStudent.age = 21;
System.out.println(mayiktStudent.name + "-" + mayiktStudent.age);
mayiktStudent.work();
}
}
单个对象内存图
多个对象指向同一个内存地址
StudentDemo.java如下:
package com.面向对象;
public class StudentDemo {
public static void main(String[] args) {
Student mayiktStudent = new Student(); // new Student()存放堆内存,mayiktStudent存放在栈内存,直接引用到堆内存地址
System.out.println(mayiktStudent);
mayiktStudent.name = "mayikt";
mayiktStudent.age = 21;
System.out.println(mayiktStudent.name + "-" + mayiktStudent.age);
mayiktStudent.work();
// Student xiaojunStudent = new Student();
Student xiaojunStudent = mayiktStudent; //将mayiktStudent的堆内存地址复制给xiaojunStudent
System.out.println(xiaojunStudent); // 可以看到这个内存地址与mayiktStudent的内存地址一样
xiaojunStudent.nage = "xiaojun";
xiaojunStudent.age = 21;
System.out.println(mayiktStudent.name + "-" + mayiktStudent.age); // 现在两个对象使用的是一个内存地址,
System.out.println(xiaojunStudent.name + "-" + xiaojunStudent.age); //所以两个对象的属性值一样
xiaojunStudent.work();
}
}
下一篇文章:成员变量与局部变量的区别