Reputation: 884
I have a basic question about initalization of object. UPDATE SomeClass is just other class. Class Foo just using methods of someClass. For example: Controller (Foo) that uses methods of DAO object(SomeClass).
What is the best approach?
public class Foo{
private SomeClass someClass;
public Foo()
{
someClass=new SomeClass();
}
public void method1(){//uses someClass}
public void method2(){//uses someClass}
}
public class Foo{
public void method1(){SomeClass someClass = new SomeClass();}
public void method2(){SomeClass someClass = new SomeClass();}
}
public class Foo{
private SomeClass someClass=new SomeClass();
public void method1(){//uses someClass}
public void method2(){//uses someClass}
}
Upvotes: 0
Views: 165
Reputation: 2653
The answer to your question really depends on how SomeClass works, and what you want it to do.
Approach 1: Creating an object instance in the constructor.
Approach 2: Creating an object instance in a method.
Approach 3: Creating an object instance in the attribute declaration.
Advantages: You get the same instance across all methods of Foo despite which constructor is called (unless you overwrite the value).
Disadvantages: If methods change the state of SomeClass, it could cause issues if you don't think of this in your design.
Approach 4: Dependency Injection. Inject the instance of SomeClass into the constructor of Foo.
Disadvantage: Calling code needs to supply an instance, which could be un-necessary depending on what you are trying to accomplish.
private mySomeClass;
public Foo(SomeClass mySomeClass)
{
this.mySomeClass = mySomeClass;
}
public void method1(){
if(mySomeClass != null) mySomeClass.runSomething();
}
Upvotes: 2
Reputation: 5654
This would depend on what you want to do with the initialized object:
SomeClass
- make it private) and get hold of the object it all the related classes using a method like SomeClass.getSingleton()
Beware that each of the above cases have their own consequences during Multithreading
Upvotes: 0