Chinaunix首页 | 论坛 | 博客
  • 博客访问: 157561
  • 博文数量: 76
  • 博客积分: 1513
  • 博客等级: 上尉
  • 技术积分: 755
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-25 15:15
文章分类

全部博文(76)

文章存档

2012年(2)

2011年(74)

我的朋友

分类: Java

2011-11-27 14:32:35

  1. public class SI {
  2. static SI test=new SI();//将类实例声明为static,这样在内存中就存在一个类实例
  3. public SI(){}
  4. public static SI getSI(){
  5.    return test;
  6. }
  7. }

  8. public class SingleInstanceTest {
  9. public static void main(String[] args)
  10. {
  11.    SI test1=SI.getSI();//test1、test2和test3在内存中是一个对象,它们应用的是同一个地址
  12.    SI test2=SI.getSI();
  13.    SI test3=SI.getSI();

  14.                 System.out.println(test1);
  15.                 System.out.println(test2);
  16.                 System.out.println(test3);
  17. }

  18. }

输出:


为了定义只能生成一个对象的类SI(SingleInstance),可以在SI中将SI实例声明为static。

阅读(1041) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~