简体   繁体   中英

Initializing ivars in Java

Is there a difference or preferred preference between declaring and setting the default ivars like so:

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?

primitive types ( int in your case) are initialized by default values automatically, so there no reason to explicitly set it to 0 ;

What about Strings and other objects: it's completely depends on your preferences. 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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