简体   繁体   English

用Java初始化ivars

[英]Initializing ivars in Java

Is there a difference or preferred preference between declaring and setting the default ivars like so: 声明和设置默认ivars之间是否存在差异或偏好设置, ivars所示:

public class Foo
{
   private int yes = 0;
   private String name = "";

   //...
   //constructors, setters, getters, etc.
}

public class Foo
    {
       private int yes;
       private String name;

       public Foo()
       {
          yes = 0;
          name = "";
       }
       //...
       //setters, getters, etc.
    }

Also, in constructors and other methods in Foo should I be setting and getting the ivars with the accessor and mutator methods or with simply assigning them directly? 另外,在Foo中的constructors和其他方法中,我应该使用accessormutator方法来设置并获取ivars ,还是直接将它们分配给它们?

primitive types ( int in your case) are initialized by default values automatically, so there no reason to explicitly set it to 0 ; 基本类型(在您的情况下为int )会自动通过默认值进行初始化,因此无需将其显式设置为0

What about Strings and other objects: it's completely depends on your preferences. Strings和其他对象呢:这完全取决于您的偏好。 I prefer not to initialize it in constructor. 不想在构造函数中初始化它。 But keep in mind that in case of initilizing fields in constructor you can handle exceptions if field initializing throws some exception 但是请记住,在初始化构造函数中的字段的情况下,如果字段初始化引发某些异常,则可以处理异常

Same thing. 一样。 Accessor and mutators methods will be needed for external classes. 外部类将需要访问器和更改器方法。

It doesn't matter and it's basically personal preference. 没关系,这基本上是个人喜好。 Java compiler copies the initialization from a class to every constructor (no extra calls, it's really a direct copy in the bytecode). Java编译器将初始化从类复制到每个构造函数(无需额外的调用,它实际上是字节码中的直接副本)。

Personally, I prefer to put the data-independent initialization to the class while I put the data that might depend on the constructor parameters to the constructor itself. 就个人而言,我更喜欢将与数据无关的初始化放入类中,而将可能依赖于构造函数参数的数据放入构造函数本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM