0
class Outer {
    static void out() {
        System.out.println("hello world");
    }
    static class Inner {
    }

    static void main(String[] args) {
        //Intellij Note: No candidates found for method call
        Outer.Inner.out();
    }
}

After running this script, the Outer.out will be executed successuful. Why? I get this info from the official doc:

The implementation of anonymous inner classes and nested classes follow Java closely, but there are some differences, e.g. local variables accessed from within such classes don’t have to be final. We piggyback on some implementation details we use for groovy.lang.Closure when generating inner class bytecode.

Anybody can explain why this script can be executed successful?

2
  • groovy dynamically looking for methods/members that are accessible for a context. method out() is accessible for inner class - this is correct for java: static class Inner { static void inn(){ out(); } }. so, in groovy when you have accessor Outer.Inner. you switching context to Inner class where out() is accessible. maybe it's a bug, but for me it sounds logical ;) you can always annotate your class or method with @groovy.transform.CompieStatic to get compilation error as in java. Commented Jun 27, 2023 at 16:52
  • Thanks for your explanation. This make sense. The official docs of java told me what the nested class can visit clearly. But the docs of groovy not explain this behavior clearly. Commented Jun 28, 2023 at 1:53

0

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.