代码块:就是用{}括起来到部分。根据应用的不同分为4类:普通代码块、构造块、静态代码块、同步代码块。
1.普通代码块:定义在方法中的代码块。
如:
- public class Ex22 {
-
- public static void main(String[] args){
-
- {
- int i = 3;
- System.out.println("局部变量为 " + i);
- }
- int i = 5;
- System.out.println("相对上面的 i 来说是全局的变量 " + i);
-
- }
-
-
- }
-
-
2.构造块:直接在类中编写的代码块。
- class Demo5{
- {
- System.out.println("构造块");
- }
- public Demo5(){
- System.out.println("构造方法");
- }
- {
- System.out.println("构造方法后的构造块");
- }
- }
- public class Ex22 {
-
- public static void main(String[] args){
- new Demo5();
- new Demo5();
-
- }
-
-
- }
-
-
-
-
-
-
对象被实例化一次构造块就执行一次;
构造块优先执行比构造方法.
3.静态代码块:static 关键字声明的代码块.
- class Demo5{
- {
- System.out.println("1构造块");
- }
- public Demo5(){
- System.out.println("2构造方法");
- }
- {
- System.out.println("3构造方法后的构造块");
- }
- static {
- System.out.println("4静态代码块");
- }
-
- }
- public class Ex22 {
- static {
- System.out.println("在主方法类中定义的代码块");
- }
-
- public static void main(String[] args){
- new Demo5();
- new Demo5();
-
- }
-
-
- }
-
-
-
-
-
-
-
-
-
- 本文来自优快云博客,转载请标明出处:http:
主方法静态代码块优先于主方法,
在普通类中静态块优先于构造块,
在普通类中构造块优先于构造方法,
静态块只实例化一次。