为了访问静态变量,我们不需要创建该类的任何对象,我们可以简单地访问变量:
class_name.variable_name;
示例程序:
import java.io.*; class Emp { // static variable salary public static double salary; public static String name = "Harsh"; } public class EmpDemo { public static void main(String args[]) { //accessing static variable without object Emp.salary = 1000; System.out.println(Emp.name + "'s average salary:" + Emp.salary); } }
输出:
Harsh's average salary:1000.0
class Example { static int a; //静态变量 int b; //实例变量 }