Java中的静态方法或静态代码块有哪些限制?


静态方法和静态块

静态方法属于类,它们将与类一起加载到内存中,无需创建对象即可调用它们。(使用类名作为引用)。

而**静态块**是用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关键字。

  • 对于静态块,不能动态控制执行顺序,它们将按声明顺序执行。

更新于:2019年10月14日

4K+ 浏览量

启动您的职业生涯

通过完成课程获得认证

开始
广告