Recently this interview question, spread the programmer each size garden, this small Samaritans excerpt organizes with everybody to study together:
Original question:
PackageCom.gxlee; Public classBase {PrivateString basename= "Base"; PublicBase () {callname (); } Public voidcallname () {System.out.println (baseName); } Static classSubextendsbase{PrivateString baseName = "Sub"; Public voidcallname () {System.out.println (baseName); } } Public Static voidMain (string[] args) {Base b=NewSub (); System.out.println (b); }}
The output of this program.
The key to solving this problem is to understand and master the loading process of the class and the invocation of the overriding method after the subclass inherits the parent class:
From the execution order of the program to answer:
1, Base B = new Sub ();
Declares a reference to the parent class variable B to the child class, and the Java ClassLoader loads the Base,sub class into the JVM;
2, the JVM for BASE,SUB members to open up memory space
At this point, the values in the Base and sub classes are null;
3. New Sub ()
Call the constructor, because the sub class inherits from the base and no custom constructor, so first call the parent class base of the parameterless construct;
4, the nature of the parent lunch structure is:
Public Base () {
Basename= "Base";
Callname ();
}
The basename assignment of the parent class is "base", and the value is called Callname () after assignment;
5, Callname is overridden in subclasses, so call the subclass Callname ();
6. Call Subclass Callname, print basename
This basename is a member variable of sub-class sub, at which time the member has not been initialized and is therefore null;
7, in fact, when the new Sub (), the actual execution process is:
Public Sub () {
Super ();
BaseName = "Sub";
}
It can be seen that callname () of the subclass has been executed before basename = "Sub" is executed, so the basename of the subclass is the default value state null;
Summarize:
come tocomments from the old Mo :
"Do not invoke virtual methods that may be overloaded in the constructor, which is extremely dangerous."
The constructor's initialization order is presumably: parent class static block, subclass static block, parent class initialization statement, parent class constructor, subclass initializer sentence class constructor.
When the parent class constructor executes, the overloaded method of the subclass is called, but the class field of the subclass is still in the newly initialized phase, and the memory layout has just been completed and only null is output.
Recently a very hot Ctrip Java engineer a face-to-face question