Java类中的静态变量在程序运行期间,其内存空间对所有该类的对象实例而言是共享的,有些时候可以以为是全局变量。因此在某些时候为了节省零碎内存开销、共享资源,可以将类中的一些变量声明为静态变量,经过下面的例子,你可以发现合理使用静态变量带来的好处:
Java代码
publicclassWeekA{ staticclassData{ privateintweek; privateStringname; Data(inti,Strings){ week=i; name=s; } } Dataweeks[]={ newData(1,"Monday"),newData(2,"Tuesay"),newData(3,"Wednesday"),newData(4,"Thursday"),newData(5,"Friday"),newData(6,"Saturday"),newData(7,"Sunday") }; publicstaticvoidmain(Stringargs[]){ finalintN=10000; WeekAweekinstance; for(inti=1;i=N;i++){ weekinstance=newWeekA(); } } } publicclassWeekA{ staticclassData{ privateintweek; privateStringname; Data(inti,Strings){ week=i; name=s; } } Dataweeks[]={ newData(1,"Monday"),newData(2,"Tuesay"),newData(3,"Wednesday"),newData(4,"Thursday"),newData(5,"Friday"),newData(6,"Saturday"),
1newData(7,"Sunday") }; publicstaticvoidmain(Stringargs[]){ finalintN=10000; WeekAweekinstance; for(inti=1;i=N;i++){ weekinstance=newWeekA(); } } }
在上面这段代码中,没有将Data weeks声明为静态变量,因此当创建WeekA对象时将会失掉10 000个weeks对象的正本,这些对象被保管在内存中,但是weeks对象中的数据却从来没有被更改过,而且十分稳定。因此,如果能使所有对象共享该数据对象是个不错的解决方法,请看下面的代码: