Java中静态变量的适用场景
Java类中的.静态变量在程序运行期间,其内存空间对所有该类的对象实例而言是共享的,有些时候可以认为是全局变量。因此在某些时候为了节省系统内存开销、共享资源,可以将类中的一些变量声明为静态变量,通过下面的例子,你可以发现合理应用静态变量带来的好处:
Java代码
public class WeekA{
static class Data {
private int week;
private String name;
Data(int i, String s) {
week= i;
name = s;
}
}
Data weeks[] = {
new Data(1, "Monday"), new Data(2, "Tuesay"), new Data(3, "Wednesday"), new Data(4, "Thursday"), new Data(5, "Friday"), new Data(6, "Saturday"), new Data(7, "Sunday")
};
public static void main(String args[]) {
final int N = 10000;
WeekA weekinstance;
for (int i = 1; i <= N; i++){
weekinstance = new WeekA ();
}
}
}
public class WeekA{
static class Data {
private int week;
private String name;
Data(int i, String s) {
week= i;
name = s;
}
}
Data weeks[] = {
new Data(1, "Monday"), new Data(2, "Tuesay"), new Data(3, "Wednesday"), new Data(4, "Thursday"), new Data(5, "Friday"), new Data(6, "Saturday"), new Data(7, "Sunday")
};
public static void main(String args[]) {
final int N = 10000;
WeekA weekinstance;
for (int i = 1; i <= N; i++){
weekinstance = new WeekA ();
}
}
}
【Java中静态变量的适用场景】相关文章: