Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top