在Java中是否存在访问成员变量的this前缀?
以下是我的HelloWorld代码:
public class HelloWorld {
public static int x = 0;
public static void main(String[] args) {
HelloWorld.x = 45;
System.out.println(HelloWorld.x);
}
}上面的代码使用/不使用类名前缀变量x。但是,如果我尝试:this.x = 45;或this->x = 45;,则会收到一个错误:
不能从静态上下文引用
非静态变量。
我知道成员变量可以在没有HelloWorld (类名)前缀的情况下访问,就像我所做的那样。但是,我想知道,如果 this 前缀存在于Java中,我如何使用它?
编辑:
另外,你能提供一个this合适的例子吗?
duffymo &字节-我非常感谢您的帮助。谢谢。
发布于 2011-07-30 19:44:50
您试图使用'this'来引用静态变量,而不是实例变量。' this '仅用于引用该类实例化对象的实例变量。您不能使用'this'来引用类中的静态变量。
当您使用' this '时,您说的是“我想引用这个类的特定实例化的变量”。另一方面,不管实例化如何,静态总是类的相同变量。
此外,引用实例变量的正确语法是由点运算符:
this.x = 42; //correct
this->x = 42; //will not compile as its not valid Java所以从本质上说,你所追求的是如下所示:
public class Foo {
private int x;
public void setX(int x) {
this.x = x;
}
public int getX() {
return this.x;
}
}
public class HelloWorld {
public static void main(String[] args)
{
Foo foo = new Foo();
foo.setX(45);
System.out.println(foo.getX());
}
}https://stackoverflow.com/questions/6885590
复制相似问题