我们可以在 Java 中的静态方法中使用“this”关键字吗?


静态方法属于该类,它们将随类一起加载到内存中。你可以在不创建对象的情况下调用它们。(使用类名作为引用)。

示例

public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("Contents of the static method");
   }
   public static void main(String args[]){
      Sample.demo();
   }
}

输出

Contents of the static method

“this”关键字用作对实例的引用。由于静态方法不属于(不拥有)任何实例,所以你无法在静态方法中使用“this”引用。如果你仍然尝试这样做,就会生成编译时错误。

示例

public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("Contents of the static method"+this.num);
   }
   public static void main(String args[]){
      Sample.demo();
   }
}

编译时错误

Sample.java:4: error: non-static variable this cannot be referenced from a static context
   System.out.println("Contents of the static method"+this.num);
                                                      ^
1 error

更新于: 05-Aug-2019

5K+ 浏览量

开启你的 事业

完成课程即可获得认证

开始
广告
© . All rights reserved.