Java 内部类

参考http://android.blog.51cto.com/268543/384844

1、成员内部类

      成员内部类,就是作为外部类的成员,可以直接使用外部类的所有成员和方法,即使是private的。同时外部类要访问内部类的所有成员变量/方法,则需要通过内部类的对象来获取。

      要注意的是,成员内部类不能含有static的变量和方法。因为成员内部类需要先创建了外部类,才能创建它自己的,了解这一点,就可以明白更多事情,在此省略更多的细节了。在成员内部类要引用外部类对象时,使用outer.this来表示外部类对象;而需要创建内部类对象,可以使用outer.inner obj = outerobj.new inner();

public class Outer { 
    public static void main(String[] args) { 
        Outer outer = new Outer(); 
        Outer.Inner inner = outer.new Inner(); 
        inner.print("Outer.new"); 
 
        inner = outer.getInner(); 
        inner.print("Outer.get"); 
    } 
 
    // 个人推荐使用getxxx()来获取成员内部类,尤其是该内部类的构造函数无参数时 
    public Inner getInner() { 
        return new Inner(); 
    } 
 
    public class Inner { 
        public void print(String str) { 
            System.out.println(str); 
        } 
    } 
} 

2、局部内部类

      局部内部类,是指内部类定义在方法和作用域内。使用outer.this来表示外部类对象注意name为final类型,局部内部类要使用形参name,必须加上final。Thinking in Java给了这么两个例子:

      定义在方法内:

public class Outer { 
    public static void main(String[] args) { 
        Outer outer = new Outer(); 
        Inner inner = outer.getInner("Inner", "gz"); 
        System.out.println(inner.getName()); 
    } 
 
    public Inner getInner(final String name, String city) { 
	class InnerImp implements Inner {
		private String nameStr = name;
		
		public String getName() {
			return nameStr;
		}
	}

	return new InnerImp(); 
    } 
} 

interface Inner { 
    String getName(); 
} 


     定义在作用域里:

public class Parcel5 { 
    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) { 
        Parcel5 p = new Parcel5(); 
        p.track(); 
    } 
} 

3、静态内部类

      嵌套内部类,就是修饰为static的内部类。声明为static的内部类,不需要内部类对象和外部类对象之间的联系,就是说我们可以直接引用outer.inner,即不需要创建外部类,也不需要创建内部类。嵌套类和普通的内部类还有一个区别:普通内部类不能有static数据和static属性,也不能包含嵌套类,但嵌套类可以。而嵌套类不能声明为private,一般声明为public,方便调用。

      静态内部类,就是修饰为static的内部类,不能引用外部类的成员和方法。不能声明为public,一般声明为private。

      静态内部类,可以包含static的成员和方法,而成员内部类不能。

      如果要生成静态内部类,outer.inner obj = new outerobj.inner();

/*
 * This file is auto-generated.  DO NOT MODIFY.
 * Original file: frameworks/base/core/java/android/os/IFregService.aidl
 */
package android.os;

public interface IFregService extends android.os.IInterface {
	/** Local-side IPC implementation stub class. */
	public static abstract class Stub extends android.os.Binder implements
			android.os.IFregService {
		private static final java.lang.String DESCRIPTOR = "android.os.IFregService";

		/** Construct the stub at attach it to the interface. */
		public Stub() {
			this.attachInterface(this, DESCRIPTOR);
		}

		/**
		 * Cast an IBinder object into an android.os.IFregService interface,
		 * generating a proxy if needed.
		 */
		public static android.os.IFregService asInterface(android.os.IBinder obj) {
			if ((obj == null)) {
				return null;
			}
			android.os.IInterface iin = (android.os.IInterface) obj
					.queryLocalInterface(DESCRIPTOR);
			if (((iin != null) && (iin instanceof android.os.IFregService))) {
				return ((android.os.IFregService) iin);
			}
			return new android.os.IFregService.Stub.Proxy(obj);
		}

		public android.os.IBinder asBinder() {
			return this;
		}

		@Override
		public boolean onTransact(int code, android.os.Parcel data,
				android.os.Parcel reply, int flags)
				throws android.os.RemoteException {
			switch (code) {
			case INTERFACE_TRANSACTION: {
				reply.writeString(DESCRIPTOR);
				return true;
			}
			case TRANSACTION_setVal: {
				data.enforceInterface(DESCRIPTOR);
				int _arg0;
				_arg0 = data.readInt();
				this.setVal(_arg0);
				reply.writeNoException();
				return true;
			}
			case TRANSACTION_getVal: {
				data.enforceInterface(DESCRIPTOR);
				int _result = this.getVal();
				reply.writeNoException();
				reply.writeInt(_result);
				return true;
			}
			}
			return super.onTransact(code, data, reply, flags);
		}

		private static class Proxy implements android.os.IFregService {
			private android.os.IBinder mRemote;

			Proxy(android.os.IBinder remote) {
				mRemote = remote;
			}

			public android.os.IBinder asBinder() {
				return mRemote;
			}

			public java.lang.String getInterfaceDescriptor() {
				return DESCRIPTOR;
			}

			public void setVal(int val) throws android.os.RemoteException {
				android.os.Parcel _data = android.os.Parcel.obtain();
				android.os.Parcel _reply = android.os.Parcel.obtain();
				try {
					_data.writeInterfaceToken(DESCRIPTOR);
					_data.writeInt(val);
					mRemote.transact(Stub.TRANSACTION_setVal, _data, _reply, 0);
					_reply.readException();
				} finally {
					_reply.recycle();
					_data.recycle();
				}
			}

			public int getVal() throws android.os.RemoteException {
				android.os.Parcel _data = android.os.Parcel.obtain();
				android.os.Parcel _reply = android.os.Parcel.obtain();
				int _result;
				try {
					_data.writeInterfaceToken(DESCRIPTOR);
					mRemote.transact(Stub.TRANSACTION_getVal, _data, _reply, 0);
					_reply.readException();
					_result = _reply.readInt();
				} finally {
					_reply.recycle();
					_data.recycle();
				}
				return _result;
			}
		}

		static final int TRANSACTION_setVal = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
		static final int TRANSACTION_getVal = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
	}

	public void setVal(int val) throws android.os.RemoteException;

	public int getVal() throws android.os.RemoteException;
}

4、匿名内部类

      匿名内部类,使用outer.this来表示外部类对象。

((Button) findViewById(R.id.start)).setOnClickListener(new Button.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
        new Thread() { 
 
            @Override 
            public void run() { 
                // TODO Auto-generated method stub 
            } 
 
        }.start(); 
    } 
});


      对比局部内部类第一个例子,就能清楚的理解局部内部类的含义:

public class Outer { 
    public static void main(String[] args) { 
        Outer outer = new Outer(); 
        Inner inner = outer.getInner("Inner", "gz"); 
        System.out.println(inner.getName()); 
    } 
 
    public Inner getInner(final String name, String city) { 
        return new Inner() { 
            private String nameStr = name; 
 
            public String getName() { 
                return nameStr; 
            } 
        };
    } 
} 

interface Inner { 
    String getName(); 
} 


      还有有参数的情况:
public class Outer { 
    public static void main(String[] args) { 
        Outer outer = new Outer(); 
        Inner inner = outer.getInner("Inner", "gz"); 
        System.out.println(inner.getName()); 
    } 
 
    public Inner getInner(final String name, String city) { 
        return new Inner(name, city) { 
            private String nameStr = name; 
 
            public String getName() { 
                return nameStr; 
            } 
        }; 
    } 
} 
 
abstract class Inner { 
    Inner(String name, String city) { 
        System.out.println(city); 
    } 
 
    abstract String getName(); 
} 

      还有一种aidl中,经常碰到的例子:

private IAcceleraterService.Stub mBinder = new IAcceleraterService.Stub() {
		
		@Override
		public void stop() throws RemoteException {
			mAccServiceManager.stopAcc();
		}
		
		@Override
		public void start() throws RemoteException {
			int flag = mAccServiceManager.startAcc(AcceleraterService.this);
			if (flag == 0) {
				Intent intent = new Intent(ACTION_START_SUCCESS);
				AcceleraterService.this.sendBroadcast(intent);
			} else {
				Intent intent = new Intent(ACTION_START_FAILURE);
				AcceleraterService.this.sendBroadcast(intent);
			}
		}
		
		@Override
		public int resume() throws RemoteException {
			return mAccServiceManager.resumeAcc();
		}
		
		@Override
		public int pause() throws RemoteException {
			return mAccServiceManager.pauseAcc();
		}
		
		@Override
		public int isAvailable() throws RemoteException {
			return mAccServiceManager.isAccAvailable();
		}
		
		@Override
		public int getHttpProxyPort() throws RemoteException {
			return mAccServiceManager.getAccHttpProxyPort();
		}
		
		@Override
		public boolean isACCEnable() throws RemoteException {
			return AcceleraterServiceManager.isACCEnable();
		}

		@Override
		public String getAccPort() throws RemoteException {
			return AcceleraterServiceManager.ACC_PORT;
		}

		@Override
		public String getVersionName() throws RemoteException {
			return AcceleraterServiceManager.getAccVersionName();
		}

		@Override
		public int getVersionCode() throws RemoteException {
			return AcceleraterServiceManager.getAccVersionCode();
		}

		@Override
		public int getCurrentStatus() throws RemoteException {
			return mAccServiceManager.getCurrentStatus();
		}

};
     IAcceleraterService.Stub是一个抽象类。

Java 内部类,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。