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

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

    Stating the obvious a bit, but with the second approach there's no need for a constructor.

提交回复
热议问题