您的位置:首页 > 编程语言 > Java开发

JAVA学习笔记8——面向对象概述2_内存分配

2015-01-20 21:23 211 查看
最近在看JAVA教学的视频,觉得老师讲的很好,同时借用源代码还有笔记来撰写本系列博客,记录自己的学习内容,同时也供看到的人学习。

好啦,开始第8篇了,这篇主要讲JAVA程序运行时的内存分析(包含继承多态的本篇暂不介绍)。

在介绍内存分析之前先来总结一下方法的一些知识:







接下来,温习一下关于变量初始化的要求:属性(成员变量)默认的初始化:整型默认为0,小数0.0,布尔默认为false,char默认为\u0000(一个unicode码,还是0),其余类型(字符串、数组、引用全是null);局部变量必须初始化,没有默认值。

下面要介绍的是JAVA程序运行的时候内存里会开辟那些空间以及分别存放程序中的什么:



下面有一个较简单和一个较复杂的实例来具体说明JAVA程序运行的时候内存分配情况:

实例1:

public class Student {
//静态的数据
String name;
int id;    //学号
int age;
String gender;
int weight;
Computer computer;
//动态的行为
public void study(){
System.out.println(name+"在學習");
}

public void sayHello(String sname){
System.out.println(name+"向"+sname+"說:你好!");
}
public static void main(String[] args){
//通过类加载器Class Loader加载Student类,加载后,在方法区就有了Student类的信息。
Student s1 = new Student();   //s1也是局部变量~
s1.name="gaoqi";
s1.study();
s1.sayHello("mashibing");

//上面已经加载过了,不用再加载了,直接拿来用。
Student s2 = new Student();
s2.name="gaoqi";
s2.study();
s2.sayHello("mashibing");
}
}
内存分配图:



对于部分内容的解释说明:我们看到没一个箭头的出发出均有一个地址,那就是他们指向(赋值/调用)的时候用到的变量的地址,众所周知,计算机的内存对于堆、栈都是为其开辟一段存储单元,任何数据结构里面的基本数据、函数代码(方法代码)都是存放在一个个存储单元里面,所以我们在访问这些数据的时候都是按照他们所在的地址进行访问的,JAVA的JVM也不例外。

实例2:

public class Student {
//静态的数据
String name;
int id;    //学号
int age;
String gender;
int weight;
Computer computer;
//动态的行为
public void study(){
System.out.println(name+"在學習");
}

public void sayHello(String sname){
System.out.println(name+"向"+sname+"說:你好!");
}
}
public class Computer {
String brand;
int cpuSpeed;
}
public class Test2 {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "高琪";
s1.age = 18;

Computer c = new Computer();
c.brand = "联想";
c.cpuSpeed = 100;

s1.computer = c;

c.brand = "戴尔";

System.out.println(s1.computer.brand);
}
}
内存分配图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: