如何在静态变量的构造函数中使用此关键字

时间:2015-01-17 20:00:42

标签: java

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();
}

在这个例子中,我们如何在构造函数中使用此关键字访问静态变量。但不是方法。这是当前对象引用的关键字,是不是?

2 个答案:

答案 0 :(得分:0)

整蛊,你实际上不在构造函数中:

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;

答案 1 :(得分:0)

static方法是属于类的方法,而不是任何特定实例。另一方面,this是引用当前实例的关键字,因此不能在static方法中使用。但是,由于x是一个静态变量,您可以使用static方法使用它:

public static void Tester() {
    System.out.print(x); // no "this" here
}