参考答案:
在 Java 中,static
是一个非常重要的关键字,它用于声明静态成员(包括静态变量、静态方法、静态块等)。使用 static
有一些需要注意的事项,下面是常见的注意点:
注意:
1public class Example { 2 static int counter = 0; 3 4 public Example() { 5 counter++; 6 } 7 8 public static void main(String[] args) { 9 Example e1 = new Example(); 10 Example e2 = new Example(); 11 System.out.println(counter); // 输出 2 12 } 13}
注意:
this
关键字,因为 this
代表的是当前对象实例,而静态方法没有对象实例的上下文。1public class Example { 2 static int counter = 0; 3 4 public static void incrementCounter() { 5 counter++; // 正确,可以访问静态变量 6 } 7 8 public void increment() { 9 counter++; // 正确,可以访问静态变量 10 } 11}
注意:
1public class Example { 2 static { 3 // 静态代码块 4 System.out.println("类加载时执行"); 5 } 6 7 public Example() { 8 System.out.println("构造方法执行"); 9 } 10 11 public static void main(String[] args) { 12 new Example(); 13 } 14}
输出:
类加载时执行
构造方法执行
注意:
1public class Outer { 2 static int x = 10; 3 4 static class Inner { 5 void print() { 6 System.out.println(x); // 访问外部类的静态变量 7 } 8 } 9}
注意:
1class Parent { 2 static void show() { 3 System.out.println("Parent show"); 4 } 5} 6 7class Child extends Parent { 8 static void show() { 9 System.out.println("Child show"); 10 } 11} 12 13public class Test { 14 public static void main(String[] args) { 15 Parent p = new Child(); 16 p.show(); // 输出 "Parent show",静态方法根据引用类型来调用 17 } 18}
volatile
等关键字来确保线程安全。1public class Example { 2 static int counter = 0; 3 4 public synchronized static void incrementCounter() { 5 counter++; 6 } 7}
import static
来导入类的静态成员,使得静态成员可以直接使用而不需要类名。注意:
1import static java.lang.Math.*; 2 3public class Test { 4 public static void main(String[] args) { 5 System.out.println(sqrt(16)); // 不需要写 Math.sqrt 6 } 7}
最近更新时间:2024-12-09