M
M
Mikhail_dev2014-09-16 12:37:03
Java
Mikhail_dev, 2014-09-16 12:37:03

(Java) Is static nested class the only object or can there be many?

Hello.
From the time of programming courses and other books like Bloch and Horstmann, I remember that static is essentially the only object (within one virtual machine).
A friend of mine said that a nested static class is not a singleton at all, so to speak, and can be in multiple instances. I could not find the answer to this matter either in the Oracle documentation for the nested class, or on stackoverflow.
The fact that this class does not contain a reference to an external object is understandable, but it does not help me in any way in thinking about this case.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
bimeg, 2014-09-16
@bimeg

The static is exactly what is needed so that there is no reference to the external class.
If you look more globally, then static means "no need for an instance of an external class."
A static field/method can be read/called without having an instance of an external class.
It is possible to create a static nested class object without having an instance of the outer class.

P
Power, 2014-09-16
@Power

The class itself (meta-entity - an instance of the class java.lang.Class<OuterClass.InnerStaticClass>) exists in a single instance, but this applies to any class (if you do not go deep into classloaders).
But you can make as many instances of the OuterClass.InnerStaticClass class as you like (this is affected by the availability of constructors, as usual): the instance of the enclosing class):

new OuterClass.InnerNonStaticClass(); // нельзя
OuterClass o = new OuterClass();
new o.InnerNonStaticClass(); // можно
new OuterClass.InnerStaticClass(); // а в случае со статическим классом так можно

Don't confuse a static class with static class fields.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question