Cannot use this in a static context

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指代的是当前的对象

在方法中定义使用的this关键字,它的值是当前对象的引用.也就是说你只能用它来调用属于当前对象的方法或者使用this处理方法中成员变量和局部变量重名的情况. 
而且,更为重要的是this和super都无法出现在static 修饰的方法中,static 修饰的方法是属于类的,该方法的调用者可能是一个类,而不是对象.如果使用的是类来调用而不是对象,则 this就无法指向合适的对象.所以static 修饰的方法中不能使用this.

### Java Static Method Usage and Characteristics Static methods belong to the class rather than specific instances of a class. These can be called without creating an instance of the class[^1]. A static method has several key features: #### Key Features A static method can operate without objects because it belongs to the class itself. This means that such methods are often used for operations where no object state is involved. For utility functions or helper methods which do not need access to instance members, declaring them as `static` saves memory by preventing multiple copies from being created with each instantiated object. ```java public class MathUtils { public static int add(int a, int b) { return a + b; } } ``` In this code snippet, the `add` function does not require any information about individual objects; therefore, marking it as static makes sense here. Static methods cannot directly call non-static (instance) methods since they don't have access to the current object (`this`). However, these may invoke other static methods within their body. If there's a necessity to use instance fields inside a static context, one must create an explicit reference to an existing object outside the scope of the static area. #### Accessing Static Methods To access a static method, either through its containing Class name or via an Object reference variable pointing towards an Instance of said Class type will work equally well due to how JVM handles internal resolution during runtime execution phase: ```java MathUtils.add(5, 3); // Using ClassName.methodName() // OR MathUtils utils = new MathUtils(); utils.add(5, 3); // Using ObjectReference.methodName(), though less common. ``` Both approaches above achieve identical results when invoking the same static member function defined earlier on `MathUtils`.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值