`
xiaobaiso
  • 浏览: 21866 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

看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 stub
System.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 stub
first f =  first.s();
first z =  first.s();
System.out.println(z.xiaobai);
f.xiaobai=100;
System.out.println(z.xiaobai);
}

}



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




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

相关推荐

Global site tag (gtag.js) - Google Analytics