Java如何创建静态变量?
类变量或static变量是用static修饰符声明的变量。一个给定的类每个static变量只有一个副本,而不管该类被实例化了多少次。
如果static更改了变量的值,则新值在类的所有实例中均可用。在final可以添加关键字来表示的数值static变量永远不会改变。
如果尝试为final变量分配新值,则会出现编译错误。
package org.nhooo.example.fundamental;public class StaticDemo {
// 静态变量
static int x = 12;
// 静态变量 with final value that never change
final static int Y = 20;
// 非静态变量
int z;
public static void main(String[] args) {
StaticDemo sd0 = new StaticDemo();
System.out.println("x before update = " + StaticDemo.x);
System.out.println("y= " + StaticDemo.Y);
sd0.z = StaticDemo.x + StaticDemo.Y;
System.out.println("z= " + sd0.z);
StaticDemo.x = 15;
System.out.println("x after update = " + StaticDemo.x);
StaticDemo sd1 = new StaticDemo();
StaticDemo sd2 = new StaticDemo();
StaticDemo.x = 20;
System.out.println("StaticDemo.x = " + StaticDemo.x);
System.out.println("sd0 = " + sd0.getX());
System.out.println("sd1 = " + sd1.getX());
System.out.println("sd2 = " + sd2.getX());
//
// 尝试将值分配给最终变量,这将导致
// 编译时间错误
//
// StaticDemo.Y = 30;
}
public int getX() {
return StaticDemo.x;
}
}
这是程序打印的输出:
x before update = 12y= 20
z= 32
x after update = 15
StaticDemo.x = 20
sd0 = 20
sd1 = 20
sd2 = 20
以上是 Java如何创建静态变量? 的全部内容, 来源链接: utcz.com/z/354223.html