本文我们主要以代码的形式来详述数据属性在内存中的布局. 代码如下:
class Person {
// 实例对象 (name / sex / age) --> 存放在对象内
public String name;
public String sex;
public int age;
public static int count1; // 静态变量在编译时已经产生, 属于类本身, 且只有一份, 存放在方法区
public final static int size = 10; // 被 final 修饰的为常量, 也属于对象, 被 final 修饰的对象后续不可更改
public static final int count2 = 100; // 静态的常量, 也属于类本身, 且只有一份, 被 final 修饰的对象后续不可更改
// 实例化成员函数
public void eat() {
int a = 999; // 局部变量
System.out.println("eat()!");
}
public void sleep() {
System.out.println("sleep()!");
}
// 静态成员函数
public static void test() {
System.out.println("test()!");
}
}
public class demo1 {
public static void main(String[] args) {
// 实例化对象 --> 产生对象, person 为对象的引用
Person person = new Person();
System.out.println(person.name);
System.out.println(person.sex);
System.out.println(person.age);
System.out.println(person.count1); // count1 为静态变量, 属于类的本身,
// 因此最好不要这样访问, 正确的访问形式如下:
System.out.println("=====================");
System.out.println(Person.count1);
System.out.println(Person.count2);
System.out.println("=====================");
person.eat();
person.sleep();
// 所有被 static 修饰的方法或者属性全部不依赖于对象.
// 因此这里如果写成 person.test() 会报错!
Person.test();
}
}
运行结果:
需要注意的三个地方:
- 被 final 修饰的对象为常量, 后续不可更改,但其仍然是对象;
- 静态变量在编译时已经产生, 属于类本身, 且只有一份, 存放在方法区;
- 静态成员函数不能访问非静态成员;
数据属性的内存布局:



