静态导入和类中的代码块

时间:2021-02-18 13:18:25   收藏:0   阅读:0
package com.moxi.wc;

import static java.lang.Math.random;
/**
 * @author Mr.Wang
 * @version 1.0
 * @since 1.8
 */
public class StaticDemo {
    public static void main(String[] args) {
        // 静态导入的方法在主函数中直接调用,在类里也是一样的
        System.out.println(random());;
        // 类中执行顺序: 静态代码块   匿名代码块  构造函数
        Demo demo = new Demo();
    }
}

class Demo{
    int b = 2;
    /*System.out.println("我也代码块"); */ // 类中不能直接写打印语句,只能有属性和方法
    static {
        System.out.println("我是静态代码块");
    }
    public Demo() {
        System.out.println("我是构造函数");
    }
    {
        int a = 1;
        System.out.println("我是匿名代码块");
        System.out.println("我打印a:" + a); // 我打印a:1
        System.out.println("我打印b:" + b); // 我打印b:2
    }
  int a = 1; // 如果把a的定义写在这上面的匿名代码块会报错的

}    

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!