Why does Java code with an inner class generates a third SomeClass$1.class file?

前端 未结 3 1973
北荒
北荒 2020-11-27 07:41

If I have an inner class, like this:

public class Test
{
    public class Inner
    {
        // code ...
    }

    public static void main(String[] args)
          


        
相关标签:
3条回答
  • 2020-11-27 07:55

    You'll also get something like SomeClass$1.class if your class contains a private inner class (not anonymous) but you instantiate it at some point in the parent class.

    For example:

    public class Person {
    
        private class Brain{
            void ponderLife() {
                System.out.println("The meaning of life is...");
            }
        }
    
        Person() {
            Brain b = new Brain();
            b.ponderLife();
        }
    }
    

    This would yield:

    Person.class
    Person$Brain.class
    Person$1.class
    

    Personally I think that's a bit easier to read than a typical anonymous class especially when implementing a simple interface or an abstract class that only serves to be passed into another local object.

    0 讨论(0)
  • 2020-11-27 07:57

    The SomeClass$1.class represent anonymous inner class

    hava a look at the anonymous inner class section here

    0 讨论(0)
  • 2020-11-27 08:17

    to build up on hhafez : SomeClass$1.class represents anonymous inner classes. An example of such a class would be

    public class Foo{
      public void printMe(){
        System.out.println("redefine me!");
      }
    }
    
    
    public class Bar {
        public void printMe() {
        Foo f = new Foo() {
            public void printMe() {
            System.out.println("defined");
            }
        };
        f.printMe();
        }
    }
    

    From a normal Main, if you called new Bar().printMe it would print "defined" and in the compilation directory you will find Bar1.class

    this section in the above code :

        Foo f = new Foo() {
            public void printMe() {
            System.out.println("defined");
            }
        };
    

    is called an anonymous inner class.

    0 讨论(0)
提交回复
热议问题