- public class Test {
- private static int n = 0;
- public static void setNum(int n) {
- this.n = n; //Cannot use this in a static context
- }
- public static void main(String[] args) {
- setNum(0);
- }
- }
意思是:this关键字不能在static静态方法中使用
因为:
Static方法是类方法,先于任何的实例(对象)存在。即Static方法在类加载时就已经存在了,但是对象是在创建时才在内存中生成。而this指代的是当前的对象
本文解析了Java中static静态方法为何不能使用this关键字。详细解释了static方法的特性,即在类加载时存在,独立于任何实例。而this关键字用于指向当前对象,因此在没有实例化的静态方法中无法正确指向对象。
2474

被折叠的 条评论
为什么被折叠?



