Accessing constructor of an anonymous class

后端 未结 10 2101
借酒劲吻你
借酒劲吻你 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:43

    If you dont need to pass arguments, then initializer code is enough, but if you need to pass arguments from a contrcutor there is a way to solve most of the cases:

    Boolean var= new anonymousClass(){
        private String myVar; //String for example
    
        @Overriden public Boolean method(int i){
              //use myVar and i
        }
        public String setVar(String var){myVar=var; return this;} //Returns self instane
    }.setVar("Hello").method(3);
    

提交回复
热议问题