1. Catch exceptions

Note:

2, static variable static

Note:

Output: callme a = 8 callme b = 11 myDemo. a = 8 myDemo. b = 11 obj1.a = 8 obj1.b = 11

3. Order of execution

This part is very important and also a difficult one! When encountering a combination of inheritance + static + code block + member variable assignment + constructor overload + polymorphism, how should we determine the execution order of assignment, code block, constructor? Code blocks have constructive code blocks, static code blocks, so is the problem getting more complicated? Learning this part is the need to understand the principle of THE JVM VIRTUAL machine, but due to the limited time of the course, so temporarily summed up the execution order method, encountered this problem is no longer afraid!

First in the main new class AnalysisTest, this class is inherited HelloA, when entering the subclass will first enter the parent class, and the parent class there are static code block and construction code block, so the implementation of static code block first! Then go back to the subclass to execute the static code block, then back to the superclass to execute the constructor code block and constructor, and finally back to the subclass to execute the constructor code block and constructor.

To summarize, if there is no inheritance, the order of execution is as follows: static code blocks construct code block constructors, where execution of code blocks in Main takes precedence over blocks in other classes created. And!!! If the same class is new multiple times in main, the static block in that class can only be executed once!! If there is inheritance, the order follows:

Output: static A static B I’m class A HelloA I’m clas B HelloB

Here’s another example:

This problem does not construct code blocks and static code blocks, so the code is more direct than the previous problem.

  • The main method is polymorphic, and work() calls subclass methods
  • The first sentence of the subclass constructor calls super() by default, the no-argument constructor of the parent class

Output: Inside programmer method, num=10, super.num=5