7 Replies Latest reply on Dec 3, 2013 9:28 PM by jschellSomeoneStoleMyAlias

    Constructor ? best practice

    svn123

      Hi folks,,

       

      this is my piece of my code. i had a doubt on the  initializing the variable inside constructor or else before the constructor.?

       

          private java.net.URL xl = Thread.currentThread().getContextClassLoader().getResource("z.xml");
        private static Logger log;    
        sSessionBean csb = (sSessionnBean)Util.getMBean("ssbean"); 
      
        public cWrapper()
      {  
      super();   
      log = Logger.getLogger(sWrapper.class.getName());
      }
      
      
      
      

       

      consider x1,csb variable these two variable declared and initialized that place itself...

      consider log variable this is declared in the appropriate declaration section and initialized in constructor.

       

      which is best to practice to initialize.?

       

      thanks

        • 1. Re: Constructor ? best practice
          TPD-Opitz

          I prefer initializing properties on declaration.

           

          I initialize in constructor either when properties depends on constructor paramers or the initialization may throw (checked) exceptions. In the latter case I declare the constructor to throw those exceptions.

           

          bye

          TPD

          • 2. Re: Constructor ? best practice
            gimbal2

            If you initialize the log in the constructor, it makes no sense that it is static. You'd have a shared static instance that could be used for all instances of cWrapper, yet that shared instance is recreated new for each cWrapper instance created :/

            • 3. Re: Constructor ? best practice
              rp0428
              consider log variable this is declared in the appropriate declaration section and initialized in constructor.

              No - it isn't. You defined 'log' as static.

              private static Logger log; 

              Therefore 'log' is initialized when the class itself is initialized. Since your code does not assign a value the variable will be initialized to 'null'.

               

              Be careful that you understand the difference between 'initialization' and 'assignment'; they are two related, but different, things.

               

              See section '8.3.2. Initialization of Fields' in the Java Language Spec

              http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.2

               

              •   If the declarator is for a class variable (that is, a static field), then the variable initializer is evaluated and the assignment performed exactly once, when the class is initialized (§12.4.2). 

              In the constructor you are merely assigning a new, non-null, value to the 'log' variable.

              this is my piece of my code. i had a doubt on the  initializing the variable inside constructor or else before the constructor.?


              which is best to practice to initialize.?

              The decision of whether to initialize instance variables and, if so, where to physically place those initial assignment statements is up to you and should depend on when you need the instance variables to have a value.

               

              The physical placement of the assignment might be before, within, or after (which you didn't mention) any particular constructor and may be performed within a method of the class or instance.

               

              See this example code from the Java Language Spec showing an assignment statement physically after the constructor:

              http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.2.3

              class Test2 {

                Test2() { k = 2; }

                int j = 1;

                int i = j;

                int k;

              }

              You have over-simplified the possibilities:

               

              1. There can be both static and instance variables - statics are ALWAYS initialized exactly once but can then, if not declared 'final' have new values assigned later in constructors or methods.

               

              2. Variables can be declared as 'final' - in which case they will be initialized and given a value only once.

               

              3. There are often multiple constructors - not just the one you have in your example. So an instance variable that needs the same common value regardless of the constructor being used would be given that value OUTSIDE of any constructor. It would be unnecessary, and poor practice, to repeat the variable assignments in every constructor.

               

              Each of the constructors could also, if required, assign a different initial value to an instance variable.

               

              4. Different class instances may need the variables initialized to different values. This is related to the previous example. A constructor may take parameters whose value is used to make an assignment to a variable. The constructor code may determine which variables to assign values to and what values to assign.

               

              5. Some instances may seldom need a variable to be initialized and when they do will initialize it within a method. For those use cases neither the variable declaration nor any of the constructors will provide an initial value.

               

              An often ask question related to yours is whether to physically put variable declarations for a class at the start of the class file or at the end. IMHO that is more of a personal preference; I don't believe there is a 'best practice'. An org will usually specify one or the other as part of their coding standards that are to be followed.

              • 4. Re: Constructor ? best practice
                svn123

                Hi,

                 

                5 points which you mentioned that is fine. can you please share an example on that.

                 

                thanks.

                • 5. Re: Constructor ? best practice
                  svn123

                  hi, is there anything i need to change my code? thanks,

                  • 6. Re: Constructor ? best practice
                    gimbal2

                    Yes, but before that you need to study the Java language more.

                    • 7. Re: Constructor ? best practice
                      jschellSomeoneStoleMyAlias

                      > which is best to practice to initialize.?

                       

                      In terms of logging it should be a member variable like the following and very likely should be the first declaration in the class unless there are strict guidelines about member ordering.

                       

                      private static final Logger log = Logger.getLogger(sWrapper.class);