Before I ask the question I like to provide the code for clarity. Below is my code for singleton class.
public class CoreData {
private boolean VarA;
private static CoreData instance = null;
protected CoreData() {
// Exists only to defeat instantiation.
}
public static CoreData getInstance() {
if(instance == null) {
instance = new CoreData();
}
return instance;
}
public boolean getVarA(){
return VarA;
}
public void setFirstTime(boolean B){
VarA = B;
}
}
Now I have few questions to ask
- What will be difference if make the member variable VarA as static?
- Can I initialize the member variable in the method getInstance()?
- What is the best practice in initializing member variables in Singleton class?
- What is the meaning of making this class as final?
- What is the meaning of making the member variable final.
I am very new to java and OOPS. I am learning it now. I would be grateful if someone answer my queries to make my knowledge better.
It will be harder to make it non singleton later
Yeah. Why not. But actually constructors are done for this.
By the best practice you should use some IoC and don’t put any code about scope in your logic code.
You should use
privateconstructor instead ofprotectedone or make itfinalto prevent creating several instances by extending. Likenew CoreData(){};I believe all variables should be final by default. Also it can help you with multi threading issues.