Instantiating object in a constructor

前端 未结 6 904
醉梦人生
醉梦人生 2020-12-28 23:43

It seems that the result of the following code is the same, so when should I use each?

public class Person {
   public Person() {
       this.family = new Fa         


        
6条回答
  •  执念已碎
    2020-12-29 00:24

    For class variables [static variable] you cannot use the first, since you want the initializtion to happen only once, and not with every time you invoke your constructor.

    For instance variables, the second is just a syntatic sugar of the first.
    Sometimes you might have to use the second - for argument constructor, which are themselves - passed to your constructor.

提交回复
热议问题