3

What will be the name of the .class file when local classes with same name are present in more than one instance method of same class? How can JVM differentiate these local classes?

Esko Luontola
  • 73,184
  • 17
  • 117
  • 128
Sheo
  • 1,034
  • 12
  • 24

5 Answers5

3

Code:

public class Test {

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

    public void method1() {
        class class1 {

        }
    }

    public void method2() {
        class class1 {

        }
    }
}

Generated classes:

Test.class
Test$1class1.class
Test$2class1.class

So it's OuterClass$(number)InnerClass

Tudor
  • 61,523
  • 12
  • 102
  • 142
  • 1
    I really can't think of a good reason to do this, though. If both classes are the same thing, by duplicating the code, you violated DRY and should consider refactoring. If they aren't the same thing, then they probably should have more descriptive names so someone can easily tell that they are different. – Thomas Owens Dec 12 '11 at 18:37
1

With both local classes and anonymous classes the compiler adds a number to the generated name.

Compiling the below code produced classes Test.class, Test$1Local.class, Test$2Local.class and Test$1Another.class so the compiler (jdk1.6.0_24) always adds a number to the name (maybe to avoid conflicts with inner classes) and if there are two local classes with the same name then it increments the number to avoid conflicts.

public class Test {
    public void foo() {
        class Local {
        }
    }

    public void bar() {
        class Local {
        }
    }

    public void baz() {
        class Another {
        }
    }
}
Esko Luontola
  • 73,184
  • 17
  • 117
  • 128
0

Consider the following class:

public class test
{
    private void meth1()
    {
        class abc{}
    }
    private void meth2()
    {
        class abc{}
    }
}

It will generate the following class files:

  1. test.class
  2. test$1abc.class
  3. test$2abc.class
Suraj Chandran
  • 24,433
  • 12
  • 63
  • 94
-1

The JVM uses the format org.package.OuterClass$InnerClass

Anonymous classes are assigned a unique number.

http://www.retrologic.com/innerclasses.doc7.html

Garrett Hall
  • 29,524
  • 10
  • 61
  • 76
-1

The format of the output .class file's name is PublicOuterClass$InnerClass.class. If the inner class is an anonymous class, then it will be replaced with a number and sequentially numbered starting with 1.

Thomas Owens
  • 114,398
  • 98
  • 311
  • 431