2011年12月28日星期三

第7天第5节: 对象数组、构造方法私有化程序分析

==代码块

主方法静态代码块优先于主方法,
在普通类中静态块优先于构造块,
在普通类中构造块优先于构造方法,
静态块只实例化一次。 ......

1. 普通代码块, why the following is differnt?
        **fail

public static void main ( String args[] ) {
int x = 50;
System.out.println("x= "+x);
{
int x= 30;                                 //fail: x is already defined in main
System.out.println("x= " + x);
}
}
        **pass

public static void main ( String args[] ) {
{
int x= 30;
System.out.println("x= " + x);
}
int x = 50;
System.out.println("x= "+x);
}
2. 构造块

class Demo
{
String name="aa";
{
System.out.println(name);   //==>always run before Demo()
}
}

2. 静态块

class Demo
{
String name="aa";
static String sname="saa";
static {
System.out.println("static kuai " + sname);
}
{
System.out.println("gou zhao kuai " + name);
}
public Demo() {
System.out.println("gou zhao function " + name);
}
}
public class testb
{
public static void main ( String args[] ) {
new Demo();
System.out.println();
new Demo();
}
}


---------- java output----------
static kuai saa
gou zhao kuai aa
gou zhao function aa

gou zhao kuai aa
gou zhao function aa





===构造方法私有化
1. Purpose: Let only one instance of a class in an application
2. example


class Demo
{
String name = "aa";
static Demo instance = new Demo();
private Demo() {
}
public void print() {
System.out.println(name);
}
public static Demo getInstance() {
return instance;
}
}

public class testb
{
public static void main ( String args[] ) {
Demo d0 = Demo.instance;                    // this one if instance is public
Demo d1 = Demo.getInstance();            // this one if instance is private
System.out.print(d1+"\t");
d1.print();
System.out.print(d1.getInstance()+"\t");
d1.getInstance().print();
System.out.print(d1.getInstance().getInstance()+"\t");
d1.getInstance().getInstance().print();
}
}


---------- java ----------
Demo@497934 aa
Demo@497934 aa
Demo@497934 aa

====对象数组

class Demo
{
String name = "aa";
Demo ( String name ) {
this.name = name;
}
}

public class testb
{
public static void main ( String args[] ) {
Demo d1[] = new Demo[2];                                      //dynamic initialization
d1[0] = new Demo("a0");
d1[1] = new Demo("a1");
for(Demo x:d1){
System.out.println(x.name);
}
Demo d2[] = { new Demo("a3"), new Demo("a4") };  //static initialization 
for(Demo x:d2){
System.out.println(x.name);
}
}
}


---------- java ----------
a0
a1
a3
a4






没有评论: