我们可以在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP