(1)
public class InitializeBlockDemo {
/**
* @param args
*/
public static void main(String[] args) {
InitializeBlockClass obj=new InitializeBlockClass();
System.out.println(obj.field);
obj=new InitializeBlockClass(300);
System.out.println(obj.field);
}
}
class InitializeBlockClass{
//下面这句在初始化块之前与之后,会影响到field字段的初始值
//public int field=100;
{
field=200;
}
public int field=100;
public InitializeBlockClass(int value){
this.field=value;
}
public InitializeBlockClass(){
(2)
class Root
{
static
{
System.out.println("Root的静态初始化块");
}
{
System.out.println("Root的普通初始化块");
}
public Root()
{
System.out.println("Root的无参数的构造器");
}
}
class Mid extends Root
{
static
{
System.out.println("Mid的静态初始化块");
}
{
System.out.println("Mid的普通初始化块");
}
public Mid()
{
System.out.println("Mid的无参数的构造器");
}
public Mid(String msg)
{
//通过this调用同一类中重载的构造器
this();
System.out.println("Mid的带参数构造器,其参数值:" + msg);
}
}
class Leaf extends Mid
{
static
{
System.out.println("Leaf的静态初始化块");
}
{
System.out.println("Leaf的普通初始化块");
}
public Leaf()
{
//通过super调用父类中有一个字符串参数的构造器
super("Java初始化顺序演示");
System.out.println("执行Leaf的构造器");
}
}
public class TestStaticInitializeBlock
{
public static void main(String[] args)
{
new Leaf();
}
}
(3)
public class StrangeIntegerBehavior
{
public static void main(String[] args)
{
Integer i1=100;
Integer j1=100;
System.out.println(i1==j1);
Integer i2=129;
Integer j2=129;
System.out.println(i2==j2);
}
}