문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top