首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

视thinking in java 的一个练习 多个引用指向同一个对象

2012-10-24 
看thinking in java 的一个练习多个引用指向同一个对象在工程1中 :package one?public class first{publi

看thinking in java 的一个练习 多个引用指向同一个对象

在工程1中 :

package one;

?

public class first

{

public int i=2;

public first()

{

super();

// TODO Auto-generated constructor stub

System.out.println("xiaobai");

}

?

/**

* @param args

*/

public static void main(String[] args)

{

// TODO Auto-generated method stub

?

}

?

}

?

?

?

package two;

?

import one.first;

?

public class second

{

?

/**

* @param args

*/

public static void main(String[] args)

{

// TODO Auto-generated method stub

first f =new first();

first z = f;

f.i=2222;

System.out.println(z.i);

}

?

}





在工程2中?package one;
public class first{ static first f = new first(); public int xiaobai=9;private first(){super();// TODO Auto-generated constructor stubSystem.out.println("first");++xiaobai;}
/** * @param args */
public static first s(){return f;}public static void main(String[] args){// TODO Auto-generated method stub
}
}



package two;
import one.first;


public class second{
/** * @param args */public static void main(String[] args){// TODO Auto-generated method stubfirst f = ?first.s();first z = ?first.s();System.out.println(z.xiaobai);f.xiaobai=100;System.out.println(z.xiaobai);}
}


虽然效果都是一样的 ,但是感觉工程2更实用一些 ,能动态的创建引用。 ??



对于工程2,在继承中、由于构造器是私有地,所以不能继承。裸购一定要继承,则必须显示申明一个构造,而且不是私有的。然后在子类中也只能使用这个构造。

热点排行