为什么在 Java 类的 main 方法中不能使用“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”引用。如果仍然尝试这样做,则会生成编译时错误。
而且,main 方法是静态的,因此不能在 main 方法中使用“this”引用。
示例
public class Sample{
int num = 50;
public static void main(String args[]){
System.out.println("Contents of the main method"+this.num);
}
}编译时错误
Sample.java:4: error: non-static variable this cannot be referenced from a static context
System.out.println("Contents of the main method"+this.num);
^
1 error
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP