You are mixing things up and making associations where there are none to be made.
Urs Waefler wrote:The following code belongs to the class RopeSwing:
It is never executed, because there is no instance. Correct?
Let me state it differently and hopefully, unambiguously. Since this block of code is not prefixed with the "static" keyword, this means that it is an
instance initialization block. Since this block is in the RopeSwing class, it is an instance initializer for instances of RopeSwing. What that means is that whenever an instance of the RopeSwing class is created, this code will be executed as though it were a part of whatever constructor was invoked. Since the only constructors that ever get invoked in that code are constructors of the
Rope class and NOT a constructor of the
RopeSwing class, then this instance initialization block will
never be executed.
What is about these two statements? I think there are two constructors. Why are the references marked as static?
There's nothing special about marking these variables static. The use of static here has
nothing to do with the invocation of Rope() constructors or the execution of code in the instance initialization block (as already explained above). The static declaration merely makes the
rope1 and
rope2 variables
class variables of the RopeSwing class, i.e., they do not "belong" to any particular instance of RopeSwing but instead are shared by
all instances of RopeSwing, therefore they "belong" to the RopeSwing
class itself (which again is why they are called
class variables)
I think your confusion comes from thinking that there's a connection between the static declaration, the Rope() constructors, and that
static instance initialization block. The connections you think exist actually do not exist. It's like thinking that just because you are wearing tennis shoes, you are going to be able to play the piano. Those two things are unrelated and there's no connection between them. These examples are purposely made this way to see if you actually know that. Real-world code would never look this way, at least code that is actually useful.