2
votes

Assume that I have two local classes with the same names, but they're defined in different methods. In what order will they compile and what names are they going to have?

class ExampleClass {

    public void test() {
        NestedClass.nestedTest2();
        NestedClass.nestedTest();

    }

    private static class NestedClass {
        private static int a;

        public static void nestedTest() {
            class Test1 {
                void method1() {}

            }
        }

        public static void nestedTest2() {
            class Test1 {
                void method2() {}
            }
        }
    }
}

Using javac command I get these compiled files

ExampleClass$NestedClass$1Test1
ExampleClass$NestedClass$2Test1

There are other files, I just don't really thing it's necessary to list them all.

The question is, how come the first file (ending with $1Test1, which is defined in nestedTest() method ) get compiled earlier than the other one (defined in method nestedTest2)? What does the order depend on? As you see I also tried to call test methods in ExampleClass to change the order, but I didn't believe it would help and it actually doesn't.

It's more compiler internal design how to proceed. The promise is that code is to be well compiled, optimized and not how is done. In order to predict the compilation order should go deep into internal and think is not so trivial. (something may be intuitive but is sure ???) - Traian GEICU
it's certain also that compiler log is reflecting exactly what happen internal : step by step ??? (maybe on some steps, but for all ??? normally it should be ... think how log it's dumped ) - Traian GEICU
Why does it matter? If you're programming to hope for a give side-effect, is that productive? Or are you trying to be a pain-in-the-neck to the programmer who has to eventually debug or modify your code? - NomadMaker
I would not expect the answer to be anything other than "it happens to be implemented this way in the compiler", but someone might post an answer anyway because the question looks reasonably interesting. - user202729
You should not expect that calling of methods affects their compilation order, but reordering the definition of nestedTest() and nestedTest2() will swap the compilation order of the contained Test1 classes too. So they are just ordered as they come in the source code. - tevemadar