类变量介绍
类变量使用注意事项和细节讨论
类方法介绍
类方法使用场景
类方法使用注意事项和细节讨论
类变量内存剖析
至于static变量到底是放在堆里面还是在方法区的静态域里面,是看JDK的版本决定的,JDK7及以下版本static变量在方法区的静态域中,
JDK7以上版本,静态域存储于定于类型的class对象宏,class对象如同堆中其他对象一样,存在于GC堆中
堆里面通过反射机制会加载一个class对象
当你的类加载的时候,它会在堆里面生成一个它的类的class对象,class对象可以拿到很多类的信息,static变量保存在class实例的尾部
static变量是对象共享,不管static变量在哪,都有两点共识(1)static变量是同一个类所有对象共享
(2)static变量,在类加载的时候就生成了
练习
练习一
class Test {
static int count = 9;
public void count() {
System.out.println("count=" + (count++));
}
public static void main(String args[]) {
new Test().count(); //9
new Test().count(); //10
System.out.println(Test.count); //11
}
}
练习二
class Person {
private int id;
private static int total = 0;
public static int getTotalPerson() {
//id++;//错误, 注销
return total;
}
public Person() {//构造器
total++; //total = 1
id = total;//id = 1
}
}
class TestPerson {
public static void main(String[] args) {
System.out.println("Number of total is " +Person.getTotalPerson()); //0
Person p1 = new Person();
System.out.println( "Number of total is "+ Person.getTotalPerson()); //1
}
}
练习三
class Person {
private int id;
private static int total = 0;
public static void setTotalPerson(int total){
// this.total = total;//错误,因为在static方法中,不可以使用this 关键字
Person.total = total;
}
public Person() {//构造器
total++;
id = total;
}
//编写一个方法,输出total的值
public static void m() {
System.out.println("total的值=" + total);
}
}
class TestPerson {
public static void main(String[] args) {
Person.setTotalPerson(3);
new Person(); //最后 total的值就是4
Person.m();//看看输出的是不是4
}
}