静态方法和静态块
静态方法属于该类,它们将与该类一起加载到内存中,您可以在不创建对象的情况下调用它们。(使用类名作为参考)。
而静态块是代码用static关键字块。通常,这些用于初始化静态成员。JVM在类加载时在main方法之前执行静态块。
示例public class Sample {
static int num = 50;
static {
System.out.println("Hello this is a static block");
}
public static void demo() {
System.out.println("Contents of the static method");
}
public static void main(String args[]) {
Sample.demo();
}
}
输出结果Hello this is a static block
Contents of the static method
静态块和静态方法的限制
静态方法您不能从静态上下文访问非静态成员(方法或变量)。
this和super不能在静态上下文中使用。
静态方法只能访问静态类型数据(静态类型实例变量)。
您不能覆盖静态方法。您可以将其隐藏。
静态块您不能从静态块返回任何内容。
您不能显式调用静态块。
如果在静态块中发生异常,则必须将其包装在try-catch对中。你不能扔它。
您不能在静态块内使用this和super关键字。
如果是静态块,则无法动态控制执行顺序,它们将按照声明的顺序执行。