我是 Java 新手。我知道static是类级别和this对象级别,但请告诉我static方法是否可以引用thisjava 中的指针?
3 回答
4
不,this在static方法/块中引用是没有意义的。Static方法可以在不创建的情况下调用,instance因此this不能用于引用instance字段。
如果你尝试放入this一个static方法,编译器会抛出一个错误说
不能在静态上下文中使用它
于 2013-09-08T16:21:34.963 回答
1
不,this不能在静态上下文中访问。June Ahsan 说了你可能需要知道的一切,但我想补充一点背景知识。
在字节码级别上,对象方法和静态方法之间的唯一区别是对象方法的第一个参数。可以通过 访问此参数this。由于静态方法缺少此参数,因此没有this.
例子:
class MyClass {
private int b;
public void myMethod(int a){
System.out.println(this.b + a);
}
public static void myStaticMethod(int a){
System.out.println(a*a); // no access to b
}
}
在字节码级别上变成(粗略地说,因为字节码看起来不像这样)
class MyClass {
int b;
}
void myMethod(MyClass this, int a){
System.out.println(this.b + a);
}
static void myStaticMethod(int a){
System.out.println(a*a); // no access to b
}
于 2013-09-08T16:37:41.507 回答
0
不,但你可以像这样在你的类中创建你的类的静态对象,
private static ClassName instance;然后你可以instance = this;在构造函数中设置它。这将可供您在静态方法中使用。
于 2013-09-08T16:36:58.030 回答