What does a class field that contains an object of this class mean?
Hello!
In the code, there is often such a construction (in any c-like language).
class One {
One instanse; //Вот эта строчка не понятна
... //Здесь дальнейшая реализация
}
Such a line is always found in the singleton and (if I understand correctly) is called a global access point. The class field itself, in which the class object is enclosed, makes me think of recursion, which is completely incomprehensible.
Questions:
- What does this field mean?
- What is this field used for?
- How is this even possible? After all, a class is the essence of a stamp, and an object is a cast from a stamp. It turns out that the stamp contains a cast? And each instance already contains an instance of itself?
- Optional - where and in what book (site) is this clearly described?
1 answers
Here in this form
class One {
One instanse;
}
This is a common property of an object. No one prevents an object from having a property of the same class to which it belongs. For example, you can implement the rhyme " Behind the tree is a tree, and behind the tree is a tree, and behind the tree is a tree, that's the end of the forest (i.e. in the last object is the field null
)". In principle, this is how you can describe any tree-like (recursive) structure. Here's a binary tree node for example:
class Node {
Node left;
Node right;
}
If we see such a
class One {
private static One instanse;
}
Then here, this field is a class field. That is, it is common to all instances of the class. Usually such constructions, together with a private constructor and the getInstance()
method:
private One(){...}
public static One getInstance() { //самая простая реализация
if(instance == null) instance = new One();
return instance;
}
Ensures that one and only one instance of this class will be created, which will be stored in the instance
field and can be separated via One.getInstance()
. I.e., singleton.