Active and passive references to classes in Java, and java references
This article focuses on active and passive references of classes in Java.
Active referenceHere, we will introduce five scenarios for active reference.
1. When the four bytecode commands "new", "getstatic", "putstatic", and "invokestatic" are executed, the class will be initialized if it is not initialized, create an object, read or set static fields, and call the static method.
2. Reflection
3. The parent class is initialized before subclass initialization.
4. Class containing the main method. The class is initialized when the VM is started.
5. When using jdk Dynamic Language Support (unknown)
Passive reference:
class SuperClass{ static{ syso("super init"); }public static int value=123;}class SubClass extends SuperClass{ static{ syso("sub init")}}public class ConstantClass{ public static final HW="helloworld";}public class NotInitialization{ main(){ syso( SubClass.value) //SuperClass sc[] =new SuperClass[10] //syso(ConstantClass.HW);}}
Output:super init 123
For access to static fields, only the class that directly defines this field will be initialized, And the subclass will not be initialized. After the first annotation is canceled, the class will run without any output, defining a reference class through an array will not trigger class initialization, but will initialize the initialization of a subclass that is automatically generated by the Virtual Machine and inherited from the object class. This class represents an array, the attributes and methods of the array are implemented in this class (length attribute and clone (). After the second comment is canceled, no output is generated. constants are placed in the constant pool during compilation, constantClass. HW is put into the constant pool of the NotInitialization class during compilation. NotInitialization does not have the symbol reference of NotInitialization.
Summary
The above is all the content about active and passive references to classes in Java. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!