Examples:
(single selection) What the output of the following code is.
public class Base {
private String basename= "base";
Public Base () {
callname ();
}
public void Callname () {
System.out.println (baseName);
}
Static class Sub extends base{
private String baseName = "Sub";
public void Callname () {
System.out.println (baseName);
}
}
public static void Main (string[] args) {
Base b = new Sub ();
}
}
A.null
B.sub
C.base
Answer: A
In order to better analyze the code to run the process, do the original code to make some changes as follows:
public class Base {
private String basename= "base";
Public Base () {
System.out.println ("constructor base:" + BaseName);
System.out.println ("Before Base callname ()-----");
Callname ();
System.out.println ("After Base callname ()-----");
}
public void Callname () {
System.out.println ("&" + BaseName);
}
Static class Sub extends base{
private String baseName = "Sub";
Public Sub () {
System.out.println ("constructor sub:" + baseName);
}
@Override public
void Callname () {
System.out.println ("#" + baseName);
}
public static void Main (string[] args) {
new Sub ();
}
}
The new Sub () within the main method is now;
Output results:
Constructor Base:base
before base callname ()-----
# null after
base callname ()-----
Constructor S Ub:sub
Then change the main method as follows:
public static void Main (string[] args) {
Base b = new Sub ();
B.callname ();
}
Output results:
Constructor Base:base
before base callname ()-----
# null after
base callname ()-----
Constructor Sub: Sub
# Sub
In Summary, the Callname () method of sub class sub is running at this time,
New Sub (); The base class object is first created in the process of creating the derived class before the derived class can be created. creating a base class is the default call to the base () method, in which the Callname () method is called, and the called Callname () method is the method in the derived class, where the derived class is not yet constructed, so the value of the variable basename is null
first member variable re-construction method, late father class sub class polymorphic Expression: A method with the same name that performs subclasses.
When a base b = new Sub () is executed, the runtime behaves as a sub class attribute, base b = new Sub () because the polymorphic B is compiled with the base class attribute , and either state invokes the base constructor execution callname () method , when the method is executed, because polymorphism behaves as a subclass attribute, the subclass is preceded by a callname () , and the subclass is not initialized (the subclass is not started until the parent class constructor is executed). executes if there is (at this point, because the subclass constructor has not yet been called, the baseName output of the subclass is null), and no longer goes to the parent class.