如果能從來,必將好好學習,天天向上
阿新 • • 發佈:2018-12-26
//張孝祥老師非常喜歡用匿名類內部類<img alt="大笑" src="http://static.blog.csdn.net/xheditor/xheditor_emot/default/laugh.gif" />
package com.bochy.innerClass; import java.util.Date; /** * 靜態內部類static inner class (also called nested class) * * 成員內部類member inner class * * 區域性內部類local inner class * * 匿名內部類anonymous inner class * * @author admin 作為public 類應該和檔名一致 原始檔中公關類名要與檔名相同 */ public class InnerClass { } /** * * 靜態內部類 * */ class StaticInner { private static int a = 4; // 靜態內部類 public static class Inner { public void test() { // 靜態內部類可以訪問外部類的靜態成員 // 並且它只能訪問靜態的 System.out.println(a); } } } class StaticInnerClassTest { public static void main(String[] args) { StaticInner.Inner inner = new StaticInner.Inner(); inner.test(); } } /*** * 非靜態成員內部類 * * @author admin * */ class MemberInner { private int d = 1; private int a = 2; // 定義一個成員內部類 public class Inner2 { private int a = 8; public void doSomething() { // 直接訪問外部類物件 System.out.println(d); System.out.println(a);// 直接訪問a,則訪問的是內部類裡的a // 如何訪問到外部類裡的a呢? System.out.println(MemberInner.this.a); } } } class MemberInnerClassTest { public static void main(String[] args) { // 建立成員內部類的物件 // 需要先建立外部類的例項 MemberInner.Inner2 inner = new MemberInner().new Inner2(); inner.doSomething(); } } /** * 區域性內部類Local Inner Class * */ class LocalInner { int a = 1; public void doSomething() { int b = 2; final int c = 3; // 定義一個區域性內部類 class Inner3 { public void test() { System.out.println("Hello World"); System.out.println(a); // 不可以訪問非final的區域性變數 // error: Cannot refer to a non-final variable b inside an inner // class defined in a different method // System.out.println(b); // 可以訪問final變數 System.out.println(c); } } // 建立區域性內部類的例項並呼叫方法 new Inner3().test(); } } class LocalInnerClassTest { public static void main(String[] args) { // 建立外部類物件 LocalInner inner = new LocalInner(); // 呼叫外部類的方法 inner.doSomething(); } } /** * 匿名內部類Anonymous Inner Class 匿名內部類就是沒有名字的區域性內部類,不使用關鍵字class, extends, * implements, 沒有構造方法。 * * 匿名內部類隱式地繼承了一個父類或者實現了一個介面。 * * 匿名內部類使用得比較多,通常是作為一個方法引數。 * */ class AnonymouseInnerClass { @SuppressWarnings("deprecation") public String getDate(Date date) { return date.toLocaleString(); } public static void main(String[] args) { AnonymouseInnerClass test = new AnonymouseInnerClass(); // 列印日期: String str = test.getDate(new Date()); System.out.println(str); System.out.println("----------------"); // 使用匿名內部類 String str2 = test.getDate(new Date() { });// 使用了花括號,但是不填入內容,執行結果和上面的完全一致 // 生成了一個繼承了Date類的子類的物件 System.out.println(str2); System.out.println("----------------"); // 使用匿名內部類,並且重寫父類中的方法 String str3 = test.getDate(new Date() { // 重寫父類中的方法 @Override @Deprecated public String toLocaleString() { return "Hello: " + super.toLocaleString(); } }); System.out.println(str3); } }