类中的static变量在创建类时会创建多次吗

//代码如下:其中小孩类中定义了一个类变量total,初始化为0,我就问,每新建一个小孩对象total不会重置为0么?求大神帮忙。
//我认为每创建一个新对象,就会执行static int total=0; 这样一来岂不是最后total==1; 可是执行结果为3. 我错在哪了?
public class demo3 { public static void main(String args[]) { Child ch1=new Child(2,"xiaoming"); ch1.joinGame(); Child ch2=new Child(4,"xiaoqiang"); ch2.joinGame(); Child ch3=new Child(6,"xiaohong"); ch3.joinGame(); System.out.println("小孩总数是:"+ch3.total); } } class Child { int age; String name; static int total; public Child(int age,String name) { this.age=age; this.name=name; } public void joinGame() { total++; System.out.println("有一个小孩加入了"); } }

这个问题其实很简单,没带static的变量属于对象,带了static的变量属于类本身,每一个类对只应一个class,在这个class被加载时,系统会在堆内存中为它分配一个空间,但每一个类可以创建出它的多个实例(也就是对象),当你在创建对像时系统会为你的每一个对像在堆内存中分配空间,这些对象都保存了对类中static的一个引用,也就是说不管你创建多少个对像,它们都指向同一个static变量,因此上面你创建了三个对像并调用了3次ch3.joinGame();你的tatol就是自加3次,所以它最终的结果是3

另外,动态变量与静态变量的区别:

动态变量在子程序中,每次调用都会从它的初始值开始调用,而不管他在函数中经历了什么变化;静态变量会从变化后的值继续改变。

原文地址:https://www.cnblogs.com/laoyangtou/p/10199375.html