下面是一些常见的Java中使用static关键字的示例:
public class MyConstants { public static final double PI = 3.14159265359; public static final String APP_NAME = "My App"; }
public class MathUtils { public static double pow(double x, double y) { return Math.pow(x, y); } public static int max(int x, int y) { return Math.max(x, y); } }
public class MySingleton { private static MySingleton instance = new MySingleton(); private MySingleton() {} public static MySingleton getInstance() { return instance; } public void doSomething() { // ... } }
public class MyStaticBlock { public static int x; public static int y; static { x = 10; y = 20; } }
在上面的例子中,静态块在类加载时执行,将x和y初始化为10和20。
public class MyOuterClass { public static int outerStaticVar = 1; public static class MyInnerClass { public void accessOuterStaticVar() { System.out.println("Outer static var: " + outerStaticVar); } } }
在上面的例子中,内部类MyInnerClass可以访问外部类的静态变量outerStaticVar。
原文链接:codingdict.net