-1

I would like to know the difference or impact at any level if we try to initialize a reference declared at class level inside a method. why would we make a reference at class level and initialize it in method scope.

second ques: what about useBox2

please help with technical justification

public class S {

    private MyBox b;

    public void useBox()
    {

        b = getBox()

        b.abc();

     }

    public synchronized void useBox2(){

        b = newBox();
    }

    private Box getBox()
    {

        return new MyBox()
    }

}
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56

2 Answers2

0

Probably what you're referring to is lazy initialization, and consists of initializing the object only when needed, to (for example) better manage memory allocation.

Using the syncronized keyword will affect how different threads access the method. Being it a class property, its "value" is going to be shared across all threads.

LppEdd
  • 20,274
  • 11
  • 84
  • 139
0

There is something wrong with the design in this question.

  1. It is better to initialize object variables during the actual object initialization. Otherwise, the code should handle all possible NullPointerException cases. I really do not like to put null checks to every possible code line.
  2. It is also not a good practice to lazily initialize a object when it is needed with this style. It gets code more messy. There is a need for null check and if object is null and call a method to initialize the object. These routine should be put to every possible code lines which need the object.

I think the above conditions make the code tightly coupled and it will lead more problems. I am questioning why this object is a class variable if it is not needed when initializing the actual object.

See also

Coupling (computer programming)

Creational design patterns

erencan
  • 3,725
  • 5
  • 32
  • 50