静态文件/变量属于该类,它将与该类一起加载到内存中。您可以在不创建对象的情况下调用它们。(使用类名作为参考)。在整个类中只有一个静态字段的副本可用,即,静态字段的值在所有对象中都相同。您可以使用static关键字定义一个静态字段。
示例public class Sample{
static int num = 50;
public void demo(){
System.out.println("Value of num in the demo method "+ Sample.num);
}
public static void main(String args[]){
System.out.println("Value of num in the main method "+ Sample.num);
new Sample().demo();
}
}
输出结果Value of num in the main method 50
Value of num in the demo method 50
静态变量的初始化
如果在类中声明静态变量,则尚未初始化它们,就像使用实例变量一样,编译器将使用默认构造函数中的默认值对其进行初始化。
示例public class Sample{
static int num;
static String str;
static float fl;
static boolean bool;
public static void main(String args[]){
System