Accessing constructor of an anonymous class

后端 未结 10 2113
借酒劲吻你
借酒劲吻你 2020-11-28 03:17

Lets say I have a concrete class Class1 and I am creating an anonymous class out of it.

Object a = new Class1(){
        void someNewMethod(){
        }
             


        
10条回答
  •  天命终不由人
    2020-11-28 03:35

    That is not possible, but you can add an anonymous initializer like this:

    final int anInt = ...;
    Object a = new Class1()
    {
      {
        System.out.println(anInt);
      }
    
      void someNewMethod() {
      }
    };
    

    Don't forget final on declarations of local variables or parameters used by the anonymous class, as i did it for anInt.

提交回复
热议问题