标签:顺序 demo dem 初始化 一个 加载类 16px 类加载 span
静态的代码块,属性和方法都会在类加载时就开始加载了,它们的加载顺序按程序先后;当实例化一个类时,会先加载普通属性>构造块>构造函数>普通方法
public class B
{
public static B t1 = new B();
public static B t2 = new B();
{
System.out.println("构造块");
}
static
{
System.out.println("静态块");
}
public static void main(String[] args)
{
B t = new B();
}
}
正确的结果是:构造块 构造块 静态块 构造块
class Demo {
int x;
static int y = 3;
// 静态代码块
static {
System.out.println("静态代码块");
}
// 定义构造代码块
{
System.out.println("我是构造代码块");
System.out.println("x=" + x);
}
//构造函数
public Demo() {
}
static void print() {
System.out.println("y=" + y);
}
void show() {
System.out.println("x=" + x + " y=" + y);
}
}
class StaticDemo {
public static void main(String[] args) {
//类名调用print方法
Demo.print();
//创建对象
Demo d = new Demo();
//给成员变量x赋值
d.x = 10;
//用对象调用show方法
d.show();
}
}
静态代码块
y=3
我是构造代码块
x=0
x=10 y=3
标签:顺序 demo dem 初始化 一个 加载类 16px 类加载 span
原文地址:https://www.cnblogs.com/52circle/p/8945257.html