ajdev
ajdev

Reputation: 21

Why doesn't compiler give warning for super.staticMethod()

I know that we should access static members in static way via class name and understand why (next code only for example, I understand it is bad practice). But why when I try access static method via super keyword there is no compiler warnings? Consider you have next code:

class Parent {
    static int staticField;
    static void staticMethod() {}
}

class Child extends Parent {
    void testStatic() {
        this.staticMethod(); // warning
        super.staticMethod(); // NO warnings
        new Child().staticMethod(); // warning
        new Parent().staticMethod(); // warning

        this.staticField++; // warning
        super.staticField++; // warning
        new Child().staticField++; // warning
        new Parent().staticField++; // warning
    }
}

So, the question is why compiler doesn't give warnings for line super.staticMethod();

Upvotes: 2

Views: 131

Answers (1)

William Kinaan
William Kinaan

Reputation: 28819

Your situation called Indirect Access To Static Method and the warning for it is off by default. To enable it:

  1. Right click on the project, go to properties.
  2. Java compiler.
  3. Error/warnings.
  4. Configure workspace settings enter image description here
  5. Check (activate) Enable project specific settings.
  6. Change the indirect access to static method to warning. enter image description here

I am using eclipse luna and it works for me

Upvotes: 2

Related Questions