代码块

package org.westos_03_代码块的概述及应用;
/*
 * 代码块的概述:
 *          在java语言中,用{}括起来的独立的代码--->代码块
 *      代码块的分类:
 *          局部代码块:出现的局部位置,作用用来限定变量的生命周期
 *          构造代码块:出现的位置是在类的成员位置,构造代码块的执行是在构造方法执行前执行!
 *              作用:将多个构造方法中的共同的代码放到构造代码块中,其实对对象进行初始化!
 *          静态代码块:也是出现在类的成员位置,在{}的前面用static修饰
 *                  static{
 *              
 *                          }  静态代码块
 *              静态跟类有关系!
 * 
 *              静态代码块特点:随着类的加载而加载,并且只执行一次
 *              构造代码块:在每次执行构造方法之前都会执行构造块
 *              
 * 
 *          面试题:
 *                  静态代码块,构造方法,以及构造代码块的优先级?
 *                      静态代码块>构造代码块>构造方法
 * */
//自定义一个类
class Code{
    //静态代码块
    static{
        int x = 1000 ;
        System.out.println(x);
    }

    //构造代码块
    {
        int x = 100;
        System.out.println(x);
    }

    //构造代码块
    {
        int y = 200 ;
        System.out.println(y);
    }

    //构造方法
    public Code(){
        System.out.println("code");
    }

    //构造方法
    public Code(int a){
        System.out.println("code");
    }

    //静态代码块
    static{
        int y = 2000;
        System.out.println(y);
    }
}

//测试类
public class CodeDemo {
    public static void main(String[] args) {
        //局部代码块
    /*  {
            int x = 10 ;
            System.out.println(x);
        }

        //此处是不访问不能访问x变量的
//      System.out.println(x);
        {
            int y = 20 ;
            System.out.println(y);
        }*/

        //创建Code类对象
        Code c = new Code() ;
        System.out.println("---------------");
        Code c2 = new Code();
        System.out.println("---------------");
        Code c3 = new Code(1) ;
    }
}
package org.westos_03_代码块的概述及应用;
//看程序写结果!
class Student {
    static {
        System.out.println("Student 静态代码块");
    }

    {
        System.out.println("Student 构造代码块");
    }

    public Student() {
        System.out.println("Student 构造方法");
    }
}
//测试类:
public class StudentDemo {
    static{
        System.out.println("高圆圆都38了,我很伤心");
    }
    public static void main(String[] args) {
        System.out.println("我是main方法");

        Student s1 = new Student();
        Student s2 = new Student();
    }
}

/*
 * 
 *2)"高圆圆都38了,我很伤心"
 *我是main方法"
 *Student 静态代码块
 *Student 构造代码块
 *Student 构造方法
 *Student 构造代码块
 *Student 构造方法
 * */
posted @ 2017-10-25 23:26  快乐的内啡肽呀  阅读(39)  评论(0)    收藏  举报