2

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

5
  • 1
    My IDE warns me about every line. What IDE do you have and have you checked that this warning isn't explicitly disabled? Commented Aug 5, 2015 at 19:52
  • super does refer to an instance -- the same instance that this refers to -- the current object. Commented Aug 5, 2015 at 20:02
  • 1
    My IDE is Eclipse Kepler, and default prefs are the next help.eclipse.org/juno/… Commented Aug 5, 2015 at 20:04
  • @ajdev I'm using IDEA and it warns me about that. Maybe Eclipse just ignores that, but it is up to the IDE if it warns about something or not. Commented Aug 5, 2015 at 20:15
  • @Tom thank you. I' m a newbie , so I just whant to make sure that this isn't some strange and specisic behavior of super keyword Commented Aug 5, 2015 at 20:25

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I tried do this. The only thing has changed - warning: Before compiler showed " The static method staticMethod() from the type Parent should be accessed in a static way ". After that (all steps that you have described) it says "The static method staticMethod() from the type Parent should be accessed directly ". But still line super.staticMethod(); has no warnings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.