static学习笔记

static常见的用法分为 “静态代码块” 和 “静态方法”
比如

static{
  //静态代码块
  ......
} 


//静态方法
public void static method{}

他们最直观的区别:

静态代码块将在类加载时主动执行,且只执行一次;

静态方法则是在类加载时加载,可以用类名直接调用,在被调用时被动执行。显而易见的是,静态方法中不能使用任何this、super(?)或非静态成员,因为尚未实例化对象。


弄清楚了这个,就顺便看一下Java中的类加载步骤:

大体分为三步:装载、链接、初始化,其中链接又可细分为校验、准备、解析(可选)


装载:查找和导入类或接口的二进制数据

校验:校验装载数据正确性

准备:给类的静态变量分配并初始化存储空间

解析:(可选)将‘符号引用’转成’直接引用‘

初始化:激活类的静态变量的初始化Java代码块(?) 和 静态Java代码块


demo:


 /**
  * 测试静态代码块和静态方法的特点;以及类的加载
  * @author guohang.ding
  * @version 2015-08-21
  */
public class staticDemoFather {


    static {
        System.out.println("this is father's static");
    }


    public static String staticFatherString;
    {
        System.out.println("staticFatherString = " + staticFatherString);
        staticFatherString = "testFather";
        System.out.println("staticFatherString = " + staticFatherString);
    }


    public staticDemoFather() {
        System.out.println("this is father's constructor and string=" + staticFatherString);
    }
}

 /**
  * static学习 子类
  * @author guohang.ding
  * @version 2015-08-21
  */
public class staticDemoChild extends staticDemoFather {


    static {
        System.out.println("this is child's static");
    }


    public static String staticChildString;
    {
        System.out.println("staticChildString = " + staticChildString);
        staticChildString = "testChild";
        System.out.println("staticChildString = " + staticChildString);
    }


    public staticDemoChild() {
        System.out.println("this is child's constructor and string=" + staticChildString);
    }
}


 /** 学习测试static的main
  * @author guohang.ding
  * @version 2015-08-21
  */
public class staticMain {


    public static void main(String[] args) {
        System.out.println("**************begin**************");
        staticDemoChild child = new staticDemoChild();
        System.out.println("***************end***************");
    }
}

//answer
**************begin**************
this is father's static
this is child's static
staticFatherString = null
staticFatherString = testFather
this is father's constructor and string=testFather
staticChildString = null
staticChildString = testChild
this is child's constructor and string=testChild
**************end**************

执行顺序显而易见


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值