Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/
JVM assigns the default value (default value) to the instance and static variables of the class, including every element in the array-without having to write the initialization value assignment statement.
Remember: local variables do not have default values and must be manually initialized! The default value assignment process is completed before the object's constructor is called.
Let's look at the following program:
Public class test {
Public static void main (string [] ARGs ){
Subclass subclass = new subclass ();
System. Out. println (subclass. getobj ());
}
}
Class superclass {
Public superclass (){
Init ();
}
Protected void Init (){
}
}
Class subclass extends superclass {
Private object OBJ; // What if it is replaced by OBJ = NULL?
Protected void Init (){
OBJ = "abcdefg ";
}
Public object getobj (){
Return OBJ;
}
Public void setobj (Object OBJ ){
This. OBJ = OBJ;
}
}
The output is abcdefg, and the output is null if OBJ = NULL.
This subclass overwrites the init () method of the parent class.
In fact, when the subclass runs the constructor, super () is used to call the constructor of the parent class, And the init () method is called in the constructor of the parent class, at this time, the subclass has the init () method that overwrites the init () method of the parent class, so the init () method of the subclass is actually called. (This also tells us that we generally do not need to construct methods to call methods that may be overwritten, which may cause many problems to the program .)
After the modification, null is output. The reason for this is a question about the Java initialization sequence:
When a new Java object (new subclass () in the main method above) is created, its internal initialization sequence is:
1. The static members and static initialization blocks of the parent class are executed in sequence in the code.
2. Subclass static members and static initialization blocks are executed in sequence in the code.
3. The parent class instance members and instance initialization blocks are executed in sequence in the code.
4. parent class Constructor
5. Subclass instance members and instance initialization blocks are executed in sequence in the code.
6. Subclass Construction Method
Let's analyze:
In private object OBJ;, 3 (no operation), 4 (abcdefg assigned), 5 (no operation), 6 (no operation) => the output is abcdefg.
In private object OBJ = NULL;, 3 (no operation), 4 (Value assignment abcdefg), 5 (modify reference to null), and 6 (no operation) are executed in sequence) => the output is null.
This is the embodiment of the polymorphism of the add () method. If you change the permission of the add () method to private, the output of both programs is null, because all private methods in the class are implicitly specified as final.
Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/