I am new to Java , and at school level, i have one query can any one better explain me the concept behind it , what it's means and when to use and why .
public class ParentClass {
private static final ParentClass ourInstance=new ParentClass();
private ArrayList<Integer> arr=new ArrayList<>();
public static ParentClass getinstance() {
return ourInstance;
}
private ParentClass() {
}
public void setList(ArrayList<Integer> al) {
arr.addAll(al);
}
public ArrayList<Integer> getList(){
return arr;
}
}
I want to focus on this line private static final ParentClass ourInstance=new ParentClass();
what it's means and when we have to declare the syntax like this ? I know we can make the class Final then no subclass can extends the final class.In the Above code the way of declaration is something different ,that's waht confused me .
private static final ParentClass ourInstance=new ParentClass();
When you declare field of a class as final then you can't reassign its value after initialisation.
What it means is you cannot execute below code:
ParentClass otherInstance = new ParentClass();
ourInstance = otherInstance; // Not allowed as ourInstance is final.
But you can perform below operations i.e. you can change fields of ourInstance by calling its setter methods: - e.g.
ourInstance.setSomeMethod(someValue); // Allowed as you are not modifying object's reference but only its properties which are not final.