10.3 代码块

10.3.1 基本介绍

10.3.2 基本语法 

 10.3.3 代码块的好处和案例演示

10.3.4 代码块使用注意事项和细节讨论 

public class CodeBlockDetail01 { 
public static void main(String[] args) { 
//类被加载的情况举例 
//1. 创建对象实例时(new) 
// AA aa = new AA(); 
//2. 创建子类对象实例,父类也会被加载, 而且,父类先被加载,子类后被加载 
// AA aa2 = new AA(); 
//3. 使用类的静态成员时(静态属性,静态方法) 
// System.out.println(Cat.n1); 
//static 代码块,是在类加载时,执行的,而且只会执行一次. 
// DD dd = new DD(); 
// DD dd1 = new DD(); 
//普通的代码块,在创建对象实例时,会被隐式的调用。 
// 被创建一次,就会调用一次。 
// 如果只是使用类的静态成员时,普通代码块并不会执行 
System.out.println(DD.n1);//8888, 静态模块块一定会执行 
} 
}
class DD { 
public static int n1 = 8888;//静态属性 
//静态代码块 
static {
System.out.println("DD 的静态代码 1 被执行...");// 
}
//普通代码块, 在 new 对象时,被调用,而且是每创建一个对象,就调用一次
//可以这样简单的,理解 普通代码块是构造器的补充 
{ 
System.out.println("DD 的普通代码块..."); 
} 
}
class Animal { 
//静态代码块 
static {
System.out.println("Animal 的静态代码 1 被执行...");// 
} 
}
class Cat extends Animal { 
public static int n1 = 999;//静态属性 
//静态代码块 
static {
System.out.println("Cat 的静态代码 1 被执行...");// 
} 
}
class BB { /
/静态代码块 
static {
System.out.println("BB 的静态代码 1 被执行...");//1 
} 
}
class AA extends BB { 
//静态代码块
static {
System.out.println("AA 的静态代码 1 被执行...");//2 
} 
}

 

 

 

public class CodeBlockDetail04 { 
public static void main(String[] args) { 
//老师说明 
//(1) 进行类的加载 
//1.1 先加载 父类 A02 1.2 再加载 B02 
//(2) 创建对象 
//2.1 从子类的构造器开始 
//new B02();//对象 new C02(); 
} 
}
class A02 { //父类 
private static int n1 = getVal01(); 
static {
System.out.println("A02 的一个静态代码块..");//(2) 
}
{ 
System.out.println("A02 的第一个普通代码块..");//(5) 
}
public int n3 = getVal02();//普通属性的初始化 
public static int getVal01() { 
System.out.println("getVal01");//(1) 
return 10; 
}
public int getVal02() { 
System.out.println("getVal02");//(6) 
return 10; 
}
public A02() {
//构造器 
//隐藏 
//super() 
//普通代码和普通属性的初始化...... 
System.out.println("A02 的构造器");//(7) 
} 
}
class C02 { 
private int n1 = 100; 
private static int n2 = 200; 
private void m1() { 
}private static void m2() { 
}
static {
//静态代码块,只能调用静态成员 
//System.out.println(n1);错误 
System.out.println(n2);//ok 
//m1();//错误 
m2(); 
}
{ 
//普通代码块,可以使用任意成员 
System.out.println(n1); 
System.out.println(n2);//ok 
m1(); 
m2(); 
} 
}
class B02 extends A02 { // 
private static int n3 = getVal03(); 
static {
System.out.println("B02 的一个静态代码块..");//(4) 
}
public int n5 = getVal04(); 
{ 
System.out.println("B02 的第一个普通代码块..");//(9)
}
public static int getVal03() { 
System.out.println("getVal03");//(3) 
return 10; 
}
public int getVal04() { 
System.out.println("getVal04");//(8) 
return 10; 
}
//一定要慢慢的去品.. 
public B02() {
//构造器 
//隐藏了 
//super() 
//普通代码块和普通属性的初始化... 
System.out.println("B02 的构造器");//(10) 
// TODO Auto-generated constructor stub 
} 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值