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

后端 未结 5 1743
后悔当初
后悔当初 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:59

    To add to Darin Dimitrov's answer, initialising the fields in line is a good idea if you have several constructor overloads, and you don't want to call other overloaded constructors for some reason.

提交回复
热议问题