What is the difference between instantiation in constructor or in field definition?

后端 未结 5 1731
后悔当初
后悔当初 2021-01-14 16:23

What is the difference between this:

public class Foo {
    private Bar bar;
    public Foo() { bar = new Bar(); }
}

and this:



        
5条回答
  •  粉色の甜心
    2021-01-14 16:58

    The difference is that in the second case field initialization happens before this/base constructor while in the first case initialization happens inside the constructor.

提交回复
热议问题