java的内部类与匿名类
提起Java内部类(Inner Class)可能很多人不太熟悉,实际上类似的概念在C++里也有,那就是嵌套类(Nested Class),关于这两者的区别与联系,在下文中会有对比。内部类从表面上看,就是在类中又定义了一个类(下文会看到,内部类可以在很多地方定义),而实际上并没有那么简单,乍看上去内部类似乎有些多余,它的用处对于初学者来说可能并不是那么显著,但是随着对它的深入了解,你会发现Java的设计者在内部类身上的确是用心良苦。学会使用内部类,是掌握Java高级编程的一部分,它可以让你更优雅地设计你的程序结构。下面从以下几个方面来介绍:
第一次见面
public interface Contents { int value();}public interface Destination { String readLabel();}public class Goods { private class Content implements Contents { private int i = 11; public int value() { return i; } } protected class GDestination implements Destination { private String label; private GDestination(String whereTo) { label = whereTo; } public String readLabel() { return label; } } public Destination dest(String s) { return new GDestination(s); } public Contents cont() { return new Content(); }}class TestGoods { public static void main(String[] args) { Goods p = new Goods(); Contents c = p.cont(); Destination d = p.dest("Beijing"); }}outerObject=new outerClass(Constructor Parameters);outerClass.innerClass innerObject=outerObject.new InnerClass(Constructor Parameters);
public class Goods { private valueRate=2; private class Content implements Contents { private int i = 11*valueRate; public int value() { return i; } } protected class GDestination implements Destination { private String label; private GDestination(String whereTo) { label = whereTo; } public String readLabel() { return label; } } public Destination dest(String s) { return new GDestination(s); } public Contents cont() { return new Content(); }}public class Goods1 { public Destination dest(String s) { class GDestination implements Destination { private String label; private GDestination(String whereTo) { label = whereTo; } public String readLabel() { return label; } } return new GDestination(s); } public static void main(String[] args) { Goods1 g= new Goods1(); Destination d = g.dest("Beijing"); }}public class Goods2{ private void internalTracking(boolean b) { if(b) { class TrackingSlip { private String id; TrackingSlip(String s) { id = s; } String getSlip() { return id; } } TrackingSlip ts = new TrackingSlip("slip"); String s = ts.getSlip(); } } public void track() { internalTracking(true); } public static void main(String[] args) { Goods2 g= new Goods2(); g.track(); }}public interface Pool extends TimerListener{ //初始化连接池 public boolean init(); //销毁连接池 public void destory(); //取得一个连接 public Connection getConn(); //还有一些其他的功能,这里不再列出 ……}public class PoolConn{ private Connection conn; private boolean isUse; private long lastAccess; private int useCount; ……}public class ConnectPool implements Pool{ //存在Connection的数组 private PoolConn[] poolConns; //连接池的最小连接数 private int min; //连接池的最大连接数 private int max; //一个连接的最大使用次数 private int maxUseCount; //一个连接的最大空闲时间 private long maxTimeout; //同一时间的Connection最大使用个数 private int maxConns; //定时器 private Timer timer; public boolean init() { try { …… this.poolConns = new PoolConn[this.min]; for(int i=0;i<this.min;i++) { PoolConn poolConn = new PoolConn(); poolConn.conn = ConnectionManager.getConnection(); poolConn.isUse = false; poolConn.lastAccess = new Date().getTime(); poolConn.useCount = 0; this.poolConns[i] = poolConn;}……return true; } catch(Exception e) { return false;}}……private class PoolConn{ public Connection conn; public boolean isUse; public long lastAccess; public int useCount;}}try { String[] divisionData = null; conn = manager.getInstance().getConnection(); stmt = (OracleCallableStatement)conn.prepareCall("{ Call PM_GET_PRODUCT.HEADER_DIVISION(?, ?) }"); stmt.setLong(1 ,productId.longValue() ); stmt.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR); ; stmt.execute(); ResultSet rs = stmt.getCursor(2); int i = 0 ; String strDivision = ""; while( rs.next() ) { strDivision += rs.getString("DIVISION_ID") + "," ; } int length = strDivision.length() ; if(length != 0 ) { strDivision = strDivision.substring(0,length - 1); } divisionData = StringUtil.split(strDivision, ",") ; map.put("Division", strDivision ) ; LoggerAgent.debug("GetHeaderProcess","getDivisionData","getValue + " + strDivision +" " + productId) ; }catch(Exception e) { LoggerAgent.error("GetHeaderData", "getDivisionData", "SQLException: " + e); e.printStackTrace() ; }finally { manager.close(stmt); manager.releaseConnection(conn); }public interface DataManager{ public void manageData();}public class DataTemplate{ public void execute(DataManager dm) { try { dm.manageData(); } catch(Exception e) { LoggerAgent.error("GetHeaderData", "getDivisionData", "SQLException: " + e); e.printStackTrace() ; }finally { manager.close(stmt); manager.releaseConnection(conn); } }}new DataTemplate().execute(new DataManager(){ public void manageData() { String[] divisionData = null; conn = manager.getInstance().getConnection(); stmt = (OracleCallableStatement)conn.prepareCall("{ Call PM_GET_PRODUCT.HEADER_DIVISION(?, ?) }"); stmt.setLong(1 ,productId.longValue() ); stmt.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR); ; stmt.execute(); ResultSet rs = stmt.getCursor(2); int i = 0 ; String strDivision = ""; while( rs.next() ) { strDivision += rs.getString("DIVISION_ID") + "," ; } int length = strDivision.length() ; if(length != 0 ) { strDivision = strDivision.substring(0,length - 1); } divisionData = StringUtil.split(strDivision, ",") ; map.put("Division", strDivision ) ; LoggerAgent.debug("GetHeaderProcess","getDivisionData","getValue + " + strDivision +" " + productId) ;}});public interface SortAlgor{ public void sort(int[] is);}public void printSortedArray(int[] is,SortAlgor sa){ …… sa.sort(is); for(int i=0;i<is.length;i++) { System.out.print(is[i]+” “);}System.out.println();}printSortedArray(is,new SortAlgor(){ public void sort(is) { int k = 0; for(int i=0;i<is.length;i++) { for(int j=i+1;j<is.length;j++) { if(is[i]>is[j]) { k = is[i]; is[i] = is[j]; is[j] = k; } } }}});spinner2.addChangeListener(new ChangeListener(){public void stateChanged(ChangeEvent e){System.out.println("Source: " + e.getSource());}});Arrays.sort(emps,new Comparator(){ Public int compare(Object o1,Object o2) { return ((Employee)o1).getServedYears()-((Employee)o2).getServedYears();}});package polyFactory;public interface Shape {public void draw();public void erase();}package polyFactory;import java.util.HashMap;import java.util.Map;public abstract class ShapeFactory {protected abstract Shape create();private static Map factories = new HashMap();public static void addFactory(String id,ShapeFactory f){ factories.put(id,f);}public static final Shape createShape(String id){ if(!factories.containsKey(id)) { try { Class.forName("polyFactory."+id); } catch(ClassNotFoundException e) { throw new RuntimeException("Bad shape creation : "+id); } } return ((ShapeFactory)factories.get(id)).create();}}package polyFactory;public class Circle implements Shape {public void draw() { // TODO Auto-generated method stub System.out.println("the circle is drawing...");}public void erase() { // TODO Auto-generated method stub System.out.println("the circle is erasing...");}private static class Factory extends ShapeFactory{ protected Shape create() { return new Circle(); }}static {ShapeFactory.addFactory("Circle",new Factory());}}package polyFactory;public class Square implements Shape {public void draw() { // TODO Auto-generated method stub System.out.println("the square is drawing...");}public void erase() { // TODO Auto-generated method stub System.out.println("the square is erasing...");}private static class Factory extends ShapeFactory{ protected Shape create() { return new Square(); }}static {ShapeFactory.addFactory("Square",new Factory());}}String[] ids = new String[]{"Circle","Square","Square","Circle"}; for(int i=0;i<ids.length;i++) { Shape shape = ShapeFactory.createShape(ids[i]); shape.draw(); shape.erase(); }