Accessing constructor of an anonymous class

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

    You can have a constructor in the abstract class that accepts the init parameters. The Java spec only specifies that the anonymous class, which is the offspring of the (optionally) abstract class or implementation of an interface, can not have a constructor by her own right.

    The following is absolutely legal and possible:

    static abstract class Q{
        int z;
        Q(int z){ this.z=z;}
        void h(){
            Q me = new Q(1) {
            };
        }
    }
    

    If you have the possibility to write the abstract class yourself, put such a constructor there and use fluent API where there is no better solution. You can this way override the constructor of your original class creating an named sibling class with a constructor with parameters and use that to instantiate your anonymous class.

    0 讨论(0)
  • 2020-11-28 03:50

    Yes , It is right that you can not define construct in an Anonymous class but it doesn't mean that anonymous class don't have constructor. Confuse... Actually you can not define construct in an Anonymous class but compiler generates an constructor for it with the same signature as its parent constructor called. If the parent has more than one constructor, the anonymous will have one and only one constructor

    0 讨论(0)
  • 2020-11-28 03:52

    I know the thread is too old to post an answer. But still i think it is worth it.

    Though you can't have an explicit constructor, if your intention is to call the constructor of the super class, then the following is all you have to do.

    StoredProcedure sp = new StoredProcedure(datasource, spName) {
        {// init code if there are any}
    };
    

    This is an example of creating a StoredProcedure object in Spring by passing a DataSource and a String object.

    So the Bottom line is, if you want to create an anonymous class and want to call the super class constructor then create the anonymous class with a signature matching the super class constructor.

    0 讨论(0)
  • 2020-11-28 03:54

    Here's another way around the problem:

    public class Test{
    
        public static final void main(String...args){
    
            new Thread(){
    
                private String message = null;
    
                Thread initialise(String message){
    
                    this.message = message;
                    return this;
                }
    
                public void run(){
                    System.out.println(message);
                }
            }.initialise(args[0]).start();
        }
    }
    
    0 讨论(0)
提交回复
热议问题