What's the difference between an instance initializer and a constructor?

前端 未结 3 1873
走了就别回头了
走了就别回头了 2020-12-10 01:19

Just wondering about the reason of compiling code like this:

class MyClass extends AnotherClass {
  {
    MySecondClass object = new MySecondClass();
    obj         


        
3条回答
  •  感动是毒
    2020-12-10 01:59

    The code inside the braces with no names will be part of the constructor of the class and be executed before the logic contained in the class constructor.

    Quick example:

    public class Foo {
        {
            System.out.println("Before Foo()");
        }
    
        public Foo() {
            System.out.println("Inside Foo()");
        }
    
        {
            System.out.println("Not After Foo()");
        }
    }
    

提交回复
热议问题