Java-6.2 inheritance (Generalization) (2)
Next, go to the previous chapter.
(4) No parameter constructor Initialization
Here we will talk about the initialization topic, especially the initialization of the base class. What will happen to the parent class?
Continue to use the above code, and we will make some streamlining.
package com.ray.testobject;public class Test {public static void main(String[] args) {new Sub();}}class Father {public Father() {System.out.println(create father);}}class Sub extends Father {public Sub() {System.out.println(create Sub);}}
Output:
Create father
Create Sub
Why?
In fact, during the compilation process, the compiler has added a new hidden parent class to the subclass. Therefore, although we are only a new subclass, the parent class is also new.
Note that the parent class is new before the subclass.
For the execution sequence, let's try another experiment. When it comes to sequence, we must introduce static code blocks, because this is also the key.
package com.ray.testobject;public class Test {public static void main(String[] args) {new Sub();}}class Father {private static int id;static {System.out.println(id: + id);System.out.println(a);}public Father() {System.out.println(create father);}}class Sub extends Father {private static String name;static {System.out.println(name: + name);System.out.println(b);}public Sub() {System.out.println(create Sub);}}
Output:
Id: 0
A
Name: null
B
Create father
Create Sub
The execution sequence is displayed in the output result:
1. Static attribute domain
2. Static code block
3. parent class Constructor
4. Subclass Constructor
(5) parameter constructor Initialization
We have discussed the absence of parameters above. Let's talk about the absence of parameters.
Note:
1. The subclass must have a constructor with relevant parameters.
2. the constructor must reference the super (parent class) constructor.
Package com. ray. testobject; public class Test {public static void main (String [] args) {}} class Father {public Father (int id) {System. out. println (create father) ;}} class Sub extends Father {public Sub (int id) {super (id); // if no such sentence exists, an error is returned, the constructors related to the parent class cannot be found. System. out. println (create Sub);} public Sub (int id, String name) {super (id); // if no such sentence exists, an error is returned, the constructors related to the parent class cannot be found. System. out. println (create Sub );}}
Just like the sub constructor, the constructor must call super () as long as there are related parameter IDS (it doesn't matter if there are other parameters ().