Suppose I want to have a bunch of private static objects in a class, but they are complicated objects and I would like to use a specific function to initialize them with some parameters. Ideally, I would write code like this:
public class TestClass{
private Class ComplicatedObject{
private int anInteger;
private String aString;
public ComplicatedObject(int inputInt,String inputString){
anInteger = inputInt;
aString = inputString;
}
public void someMethod(){
//do a thing
}
}
private void MakeAThing(ComplicatedObject theThing, int someInt,int someString){
theThing = new ComplicatedObject(someInt,someString);
//do extra stuff that one might want to do here
}
private static ComplicatedObject IMPORTANT_OBJECT;
public TestClass(){
MakeAThing(IMPORTANT_OBJECT, 0,"Test");
IMPORTANT_OBJECT.someMethod();
}
}
This will crash because (as far as I understand Java) when I call someMethod() on IMPORTANT_OBJECT, IMPORTANT_OBJECT is actually null - the MakeAThing method did create a new object, but only its internal reference (theThing) actually referenced the new object. The reference for IMPORTANT_OBJECT is still null.
Is there any way I can write a method that will change the reference for IMPORTANT_OBJECT to reference a new object?
(yes, I know that one easy solution would be to just say IMPORTANT_OBJECT = new Object(); and then add the parameters later, but this will make my code really messy (there are many "important objects") and if there is another way I'd much prefer it.)
Objectthat has parameters. Your question is very unclear. Please update your question to include a minimal reproducible example. I.e. code that actually compiles.private static IMPORTANT_OBJECT;You need to define a type at compilation, otherwise it won't compile.theThing, change it toIMPORTANT_OBJECTand remove the first parameter ofTestClass#MakeAThing.MakeAThinggoing to not depend on anything in theTestClassconstructor like in your example? If so, why not just makeMakeAThingreturn the object and just initializeIMPORTANT_OBJECTdirectly in the declaration:private static ComplicatedObject IMPORTANT_OBJECT = MakeAThing(...);. If the arguments depend on something in theTestClassconstructor, then how do you know that two invocations of theTestClassconstructor won't give different arguments?