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

In this example how can we access a static variable using this keyword inside constructor. But not in methods. this is keyword for current object reference, is n't it?

Bruce
  • 8,609
  • 8
  • 54
  • 83

2 Answers2

0

Tricky, you are actually not in a constructor:

public static void Tester() { // line 8
    System.out.print(this.x); // compilation error
}

As you can see this is actually a static method named Tester (pretty confusing code, a good reason why method names should start with lowercase letters and classnames and constructor names start with an uppercase letter).

If you remove static void from the declaration you will be able to access the non-static members correctly:

public Tester() { // Now this is a constructor
    System.out.print(this.x); // no compilation error
}

Furthermore, the variable now does not have to be static (it shouldn't). You can just declare it as an instance variable like this:

private int x;

If you simply wish to access the static version of x, just write

Tester.x = 5;

// or from a static method in class Tester
x = 5;
wassgren
  • 18,651
  • 6
  • 63
  • 77
0

A static method is a method that belongs to the class, not to any specific instance. this, on the other hand, is a keyword referring to the current instance, so it cannot be used in a static method. However, since x is a static variable, you can use it from a static method:

public static void Tester() {
    System.out.print(x); // no "this" here
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350