harukaeru
harukaeru

Reputation: 713

When compiling codes with inner class, why the strange output file is created?

I compiled this code and then, TestInner$1.class emerged.

I know ~~~$1.class indicates that file has "anonymous class."

But I don't understand the reason why this class file made. I want to know the reason.

Here is the code.

public class TestInner {
    private static class Inner { }

    public static void main(String[] args){
         new Inner();
    }
}

I tried another version removed "private" identifier, like the following.

public class TestInner {
    static class Inner { }

    public static void main(String[] args){
         new Inner();
    }
}

I'd imagined that this code also would make TestInner$1.class file.

However it didn't create the file.

In addition, the following code, added Constructor, also didn't make TestInner$1.class.

public class TestInner {
    private static class Inner {
        Inner(){ }
    }

    public static void main(String[] args){
         new Inner();
    }
}

I have no idea, so can anyone help me?

EDIT:

I found the same question and it solved. Thank you for your helping.

Why is an anonymous inner class containing nothing generated from this code?

Upvotes: 3

Views: 283

Answers (1)

Jason C
Jason C

Reputation: 40336

None of your examples have anonymous inner classes. None of them will produce a file named TestInner$1.class. All of them will produce a file named TestInner$Inner.class.

The following example shows an anonymous inner class and will produce TestInner$1.class:

public class TestInner {
    public static void main(String[] args){
         new Object() {
             @Override public String toString () {
                 return "ninja";
             }
         };
    }
}

I'm not sure where your TestInner$1.class came from but I'm guessing it's left over from previous experiments you were doing.


Update 1: I can confirm that without using Eclipse I get TestInner$1.class (in addition to TestInner$Inner.class -- 3 files are produced) for the first example but not for the last two, just like you are seeing. Will update when I find out why. When compiled via Eclipse, TestInner$1.class is never produced.


Update 2: OP found solution in Why is an anonymous inner class containing nothing generated from this code?.

Upvotes: 4

Related Questions