JAVA访问权限控制-私有构造方法 2009/07/14 后端杂文hidehai发表留言 创建一个名为ConnectionManager的类,该类管理一个元素为Connection对象的固定数组, 不能直接的创建Connetion对象只能通过ConnectionManager的某个static方法来获取他们. package cn.0x32.test.access; class Connection { private static int count; private Connection(){ System.out.println("当前对象个数:"+count); } //获取状态 public int getState(){ return count; } public static Connection makeconnect(){ count++; return new Connection(); } } public class ConnectionManager{ static Connection[] c=new Connection[3]; public static Connection getConnection(){ int len = 0; int w =getTheNum(len); Connection c1; if(w!=-1){ c1 = c[w]; c[w]=null; }else{ c1 = null; } return c1; } public static int getTheNum(int i){ if(i==c.length-1){ System.out.println("mjj"); return -1; } if(null!=c[i]){ System.out.println("取走1个"+i); return i; }else{ return getTheNum(i+1); } } public static Connection[] setConnection(){ for(int i =0 ; i< c.length; i++){ c[i]=Connection.makeconnect(); System.out.println("设置对象"+(i+1)+"个"); } return c; } public static void main(String[] args){ ConnectionManager cm = new ConnectionManager(); cm.setConnection(); cm.getConnection(); cm.getConnection(); cm.getConnection(); cm.getConnection(); cm.getConnection(); cm.getConnection(); } } Related posts: 昨天去面试了一个新的公司 笔记:java中final关键字实例代码 MyEclipse 7.0M 注册算法 List分页代码-JAVA