Static code block with static modification:
Class Demo {{System.out.println ("1, building block. ");} Static{system.out.println ("0, Static code block. ");} Public Demo () {System.out.println ("2), constructor method. ");}} public class Demo01{static{system.out.println ("code block defined in the class where the Main method resides.") ");} public static void Main (String args[]) {new demo (); new demo (); new demo ();}}
Run as follows:
0, Static code block.
1, building blocks.
2, the construction method.
1, building blocks.
2, the construction method.
1, building blocks.
2, the construction method.
From the running results of the program, it can be found that static code blocks take precedence over the main method execution, whereas static blocks of code defined in the class take precedence over the construction block execution, and no matter how many objects are produced, the static code block executes only once.
Second, with static modified class:
Static in Java is typically used to modify member variables or functions. But there is a special use of static to decorate the inner class, the ordinary class is not allowed to declare static, only the inner class can be. An inner class that is modified by static can be used directly as a normal class without the need to instantiate an external class (see code below )
Class Outerclass {public static class innerclass{ Innerclass () { System.out.println ("============= I am an internal class ' Innerclass ' ============= '); }}} public class Teststaticclass {public static void Main (string[] args) { //Do not need new one outclass new Outerclass.innerclass (); } }
Run as follows:
============= I am an internal class ' Innerclass ' =============
If the interclass is not decorated with static, it can only be called as follows:
Class Outerclass {public class innerclass{ innerclass () { System.out.println ("============= I am an internal class ' Innerclass ' ============= '); }}} public class Teststaticclass {public static void Main (string[] args) { //outclass need to be an instance of Mr. Outerclass OC = new Outerclass (); Oc.new innerclass (); }
Therefore, there is a static modification of the inner class, the outer class can invoke the method of the inner class when it is not instantiated, and when there is no static modification, the outer class must be instantiated before being called.
Favorite children's shoes can pay attention to me!
java--static Keywords Small Research