Java Post-class jobs
a . Run Testinherits.java The example, observe the output, note that the call relationship between the parent class and the subclass constructs a method, modifies the code of parent constructor method, and explicitly calls the other constructor of grandparent, notice whether the calling code is the first sentence, the impact is significant!
1. Source code:
class Grandparent {
Public Grandparent () {
System. out. println ("grandparent Created.");
}
Public Grandparent (String string) {
System. out. println ("Grandparent created.string:" + String);
}
}
class Parent extends grandparent {
Public Parent () {
Super ("hello.grandparent.");
System. out. println ("Parent Created");
Super ("hello.grandparent.");
}
}
class Child extends Parent {
Public Child () {
System. out. println ("Child Created");
}
}
Public class testinherits {
Public Static void Main (String args[]) {
Child C = new child ();
}
}
2. Experimental results:
3. Conclusion: By super calling the base class construction method, it must be the first statement in the subclass construction method.
4. thinking: Why must the constructor of the subclass be called before the constructor of the child class is run? Can you turn around? Why can't it be reversed?
Cause: The constructor is used to initialize the object when the object is created, and with the new operator when creating the statement for the object. The subclass has member variables and member methods of the parent class, and if not called, the member variables and member methods inherited from the parent class are not properly initialized. Can not be called in turn, the parent class does not know what the child class has a variable, resulting in the child class is not properly initialized, the program error.
two . empty class without any member variables
See Explorationjdksource.java example, this example defines a Class A, which does not have any Members: Class A {}
1. Source code:
Public class Explorationjdksource {
Public Static void Main (string[] args) {
System. out. println (new A ());
}
}
class a{}
2. Results:
3. Results Analysis:
in the preceding example,the main method actually calls the public void println (Object x), which internally invokes the ValueOf method of the String class . the ValueOf method internally calls the Object.ToString method: public String toString ()
{return getclass (). GetName () + "@" + integer.tohexstring (Hashcode ());}
The Hashcode method is a local method, implemented by the JVM Designer: public native int hashcode ();
Java 7 hands-on brain