[英]how this keyword works inside constructor for static variable [duplicate]
这个问题已经在这里有了答案:
public class Tester {
static int x = 4;
public Tester() {
System.out.print(this.x); //no error
Tester();
}
public static void Tester() { // line 8
System.out.print(this.x); // compilation error
}
public static void main(String... args) { // line 12
new Tester();
}
在此示例中,我们如何在构造函数中使用此关键字访问静态变量。 但不是方法。 这是当前对象引用的关键字,不是吗?
整,您实际上不在构造函数中:
public static void Tester() { // line 8
System.out.print(this.x); // compilation error
}
如您所见,这实际上是一个名为Tester
的静态方法 (相当混乱的代码,这是方法名应以小写字母和类名开头,构造函数名以大写字母开头的一个很好的原因)。
如果从声明中删除了static void
,您将能够正确地访问非静态成员:
public Tester() { // Now this is a constructor
System.out.print(this.x); // no compilation error
}
此外,变量现在不必是静态的(应该不是静态的)。 您可以像这样将其声明为实例变量:
private int x;
如果您只想访问x的静态版本,只需编写
Tester.x = 5;
// or from a static method in class Tester
x = 5;
static
方法是属于该类的方法,而不是属于任何特定实例的方法。 另一方面, this
是引用当前实例的关键字,因此不能在static
方法中使用。 但是,由于x
是静态变量,因此可以从static
方法中使用它:
public static void Tester() {
System.out.print(x); // no "this" here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.