Why people rarely use an anonymous constructor in Java

Yesterday I found out an anonymous constructor in java, not an anonymous class. I haven't seen this constructor yet, so I'm looking for it on Google. As a result, I know how to use it and what it is. But there is little information about this use.

An anonymous constructor is a code block environment using a pair of curly braces. And anonymous will be run before the general constructor and run after the static block of code.

I want to know why no one is using this anonymous constructor. Are there any bad effects on our Java application when we use it?

Thanks for any help.

The following is an example of an anonymous constructor:

    public class Static_Super_Conustruct {    

    static class Base{    
        {    
            System.out.println("Base anonymous constructor");    
        }    
        public Base() {    
            System.out.println("Base() common constructor");    
        }    
        static{    
            System.out.println("Base static{} static block");    
        }    
    }    

    static class Sub extends Base{    

        {    
            System.out.println("Sub anonymous constructor");    
        }    
        public Sub() {    
            System.out.println("Sub() common constructor");    
        }    
        static{    
            System.out.println("Sub static{} static block");    
        }    
    }    

    /**  
     * @param args  
     */    
    public static void main(String[] args) {    
        new Sub();    
    }    
//  Results:    
//  Base static{}static block    
//  Sub static{}static block    
//  Base anonymous constructor   
//  Base() common constructor    `enter code here`
//  Sub anonymous constructor    
//  Sub() common constructor

}    
+4
source share
4 answers

. , , .

, . , -, , , . , . , , .

+1

, , , .

, , Base, . , .

, , , , .

0

1) , , ,

anonymous constructor {
   do A
}

regular constructor {
   do B
}

regular constructor {
    do A
    do B
}

.

2) .
, .
,
SCJP, .

0

, , , , . , .

, , . : new java.util.HashSet<String>() {{ add("foo"); add("bar"); }}. HashSet String "foo" "bar". " ", , : HashSet, - . , , .

Despite the fact that this is not the same design, it is worth noting that in order to initialize static class, there is one and the same: static { }. This thing seems more common because there is no "constructor" to initialize the class.

0
source

All Articles