java static用法
来源:互联网 发布:mac快传 编辑:程序博客网 时间:2024/05/16 08:46
Java中的静态(static)关键字只能用于成员变量或语句块,以及静态方法。其中成员变量,语句块在类加载时会自动执行,即主动执行,不需要通过对象来执行。静态方法不需要通过对象来调用,没有其他方法调用时不会被执行,属于被动执行。
执行顺序
static 语句的执行时机实在第一次加载类信息的时候(如调用类的静态方法,访问静态成员,或者调用构造函数), static 语句和 static 成员变量的初始化会先于其他语句执行,而且只会在加载类信息的时候执行一次,以后再访问该类或new新对象都不会执行
而非 static 语句或成员变量,其执行顺序在static语句执行之后,而在构造方法执行之前,总的来说他们的顺序如下
1. 父类的 static 语句和 static 成员变量
2. 子类的 static 语句和 static 成员变量
3. 父类的 非 static 语句块和 非 static 成员变量
4. 父类的构造方法
5. 子类的 非 static 语句块和 非 static 成员变量
6. 子类的构造方法
例子1:
package myProj;
public class StaticTest {
public static void main(String[] args){
staticFunection();
}
static StaticTest st = new StaticTest();
static{
System.out.println("1");
}
{
System.out.println("2");
}
public StaticTest() {
// TODO Auto-generated constructor stub
System.out.println("3");
System.out.println("a ="+ a +", b="+b);
}
public static void staticFunection(){
System.out.println("4");
}
int a = 110;
static int b = 112;
}
【输出】
2
3
a =110, b=0
1
4
例子2:
新增class
package myProj;
public class StaticTest1 {
static {
System.out.println("this is static of parent class");
}
{
System.out.println("this is not static of parent class");
}
public StaticTest1 (){
System.out.println("this is parent class");
}
}
修改StaticTest
//static StaticTest st = new StaticTest();
static StaticTest1 st = new StaticTest1();
static StaticTest1 st1 = new StaticTest1();
【输出结果】
this is static of parent class
this is not static of parent class
this is parent class
this is not static of parent class
this is parent class
1
4
其中静态代码块只被执行了一次
- java的static用法
- Java中static用法
- java的static用法
- java的static用法
- java的static用法
- JAVA中的static用法
- Java中static用法
- java的static用法
- Java static 用法
- java static的用法
- java Static 用法
- java之static用法
- 【java】static的用法
- java中的static用法
- java static 用法
- Java Static 用法总结
- 【JAVA】static用法
- Java Static 用法总结
- hdu 1021Fibonacci Again
- XPe开发初体验:XPe概述
- 首页布局
- 【SSH进阶之路】Spring的AOP逐层深入——AOP的基本原理(六)
- 用myeclipse启动服务器显示数据库连接不成功的原因
- java static用法
- 【SpringBoot】ApplicationContextInitializer接口
- linux下内存的统计和内存泄露类问题的定位
- 【SSH进阶之路】Spring的AOP逐层深入——采用注解完成AOP(七)
- Windows Embedded Standard的U盘启动
- 第一个实例:Draw
- 基于Web浏览的用户行为分析
- 为什么我要用 Node.js
- [JAVA · 初级]:7.关键字:static